利用zookeeper生成唯一id
package com.cxy.com.cxy.curator; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
import org.I0Itec.zkclient.serialize.BytesPushThroughSerializer; /**
* @Author cxy
* @Description //TODO
* @Date 2019/1/30
**/
public class IdMaker { private ZkClient client = null;
private final String server ="127.0.0.1:2181";//记录服务器的地址
private final String root ="/NameService/IdGen";//记录父节点的路径
private final String nodeName="ID";//节点的名称
private volatile boolean running = false;
private ExecutorService cleanExector = null; //删除节点的级别
public enum RemoveMethod{
NONE,IMMEDIATELY,DELAY } public void start() throws Exception { if (running)
throw new Exception("server has stated...");
running = true; init(); } public void stop() throws Exception { if (!running)
throw new Exception("server has stopped...");
running = false; freeResource(); } /**
* 初始化服务资源
*/
private void init(){ client = new ZkClient(server,,,new BytesPushThroughSerializer());
cleanExector = Executors.newFixedThreadPool();
try{
client.createPersistent(root,true);
}catch (ZkNodeExistsException e){
//ignore;
} } /**
* 释放服务资源
*/
private void freeResource(){ cleanExector.shutdown();
try{
cleanExector.awaitTermination(, TimeUnit.SECONDS); }catch(InterruptedException e){
e.printStackTrace();
}finally{
cleanExector = null;
} if (client!=null){
client.close();
client=null; }
} /**
* 检测服务是否正在运行
* @throws Exception
*/
private void checkRunning() throws Exception {
if (!running)
throw new Exception("请先调用start"); } private String ExtractId(String str){
int index = str.lastIndexOf(nodeName);
if (index >= ){
index+=nodeName.length();
return index <= str.length()?str.substring(index):"";
}
return str; } /**
* 产生ID
* 核心函数
* @param removeMethod 删除的方法
* @return
* @throws Exception
*/
public String generateId(RemoveMethod removeMethod) throws Exception{
checkRunning();
final String fullNodePath = root.concat("/").concat(nodeName);
//返回创建的节点的名称
//final String ourPath = client.createPersistentSequential(fullNodePath, null);
final String ourPath = client.createEphemeralSequential(fullNodePath, null); System.out.println(ourPath); /**
* 在创建完节点后为了不占用太多空间,可以选择性删除模式
*/
if (removeMethod.equals(RemoveMethod.IMMEDIATELY)){
client.delete(ourPath);
}else if (removeMethod.equals(RemoveMethod.DELAY)){
cleanExector.execute(new Runnable() { public void run() {
// TODO Auto-generated method stub
client.delete(ourPath);
}
}); }
//node-0000000000, node-0000000001,ExtractId提取ID
return ExtractId(ourPath);
} }
这个是工具类
package com.cxy.com.cxy.curator; /***
* @ClassName: TestIdMaker
* @Description:
* @Auther: cxy
* @Date: 2019/1/30:17:15
* @version : V1.0
*/
public class TestIdMaker {
public static void main(String[] args) throws Exception { IdMaker idMaker = new IdMaker();
idMaker.start(); try {
for (int i = ; i < ; i++) {
String id = idMaker.generateId(IdMaker.RemoveMethod.NONE);
System.out.println(id); }
} finally {
idMaker.stop(); }
}
}
这个是测试类

可以看出是唯一的,那么在电商生产中可以加上分库分表的id+在模块+userid,加上日期就是唯一的了,不管是任何请求这个id都是唯一的,即使是在分布式环境下
利用zookeeper生成唯一id的更多相关文章
- 利用zookeeper生成唯一id,通用性代码
在上篇中是写死的,这章就写出通用的 package com.cxy.com.cxy.curator; import java.util.concurrent.ExecutorService; impo ...
- PHP生成唯一ID的方法
PHP自带生成唯一id的函数:uniqid() 它是基于当前时间微秒数的 用法如下: echo uniqid(); //13位的字符串 echo uniqid("php_"); / ...
- php 生成唯一id的几种解决方法
php 生成唯一id的几种解决方法 网上查了下,有很多的方法 1.md5(time() . mt_rand(1,1000000)); 这种方法有一定的概率会出现重复 2.php内置函数uniqid ...
- PHP使用SnowFlake算法生成唯一ID
前言:最近需要做一套CMS系统,由于功能比较单一,而且要求灵活,所以放弃了WP这样的成熟系统,自己做一套相对简单一点的.文章的详情页URL想要做成url伪静态的格式即xxx.html 其中xxx考虑过 ...
- php生成唯一id/唯一标识符/唯一订单号
/** * php 生成唯一id * https://blog.csdn.net/hzqghost/article/details/18914681 */ function guid($factor= ...
- 如何使用php生成唯一ID的4种方法
php生成唯一ID的应用场景非常普遍,如临时缓存文件名称,临时变量,临时安全码等,uniqid()函数基于以微秒计的当前时间,生成一个唯一的 ID.由于生成唯一ID与微秒时间关联,因此ID的唯一性非常 ...
- PHP获取时间戳和微秒数以及生成唯一ID
microtime函数 描述:返回当前Unix时间戳和微秒数 语法:mixed microtime( [ bool $get_as_float ] ) //直接输出 echo microtime(); ...
- 根据twitter的snowflake算法生成唯一ID
C#版本 /// <summary> /// 根据twitter的snowflake算法生成唯一ID /// snowflake算法 64 位 /// 0---0000000000 000 ...
- C# 根据twitter的snowflake算法生成唯一ID
C# 版算法: using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...
随机推荐
- QT5提示can not find -lGL的解决方法
这是由于 Qt5.0 默认将OpenGL加入了工程,但是在机器上没有安装OpenGL,所以jonas只需要在机器上安装OpenGL即可 . 安装建立基本编译环境 首先不可或缺的,就是编译器与基本的 ...
- Solaris11 How-To
允许root用户使用ftp - 修改/etc/ftpd/ftpusers文件,移除或注释掉"root" - 修改/etc/proftpd.conf文件,"RootLogi ...
- 问题:Custom tool error: Failed to generate code for the service reference 'AppVot;结果:添加Service Reference, 无法为服务生成代码错误的解决办法
添加Service Reference, 无法为服务生成代码错误的解决办法 我的解决方案是Silverlight+WCF的应用,Done Cretiria定义了需要在做完Service端的代码后首先运 ...
- The R Project for Statistical Computing
[Home] Download CRAN R Project About R Contributors What’s New? Mailing Lists Bug Tracking Conferenc ...
- LNMP 1.1 php编译安装
LNMP 是 Linux nginx mysql php nginx和apache一样也是一种web服务.在静态web服务中nginx更胜一筹.在动态中不比apache有优势. LNMP的mysql ...
- wait命令
wait命令用来等待指令的指令,直到其执行完毕后返回终端.该指令常用于shell脚本编程中,待指定的指令执行完成后,才会继续执行后面的任务.该指令等待作业时,在作业标识号前必须添加备份号"% ...
- 关于android studio中使用class.forname()方法动态获取类实例报NO CLASS FOUND异常的几种处理方法
最近在做一个项目的时候需要用到反射来回调子类的方法,但是在反射过程中总是在class.forname()方法抛出NO CLASS FOUND异常,经过几部检查,问题解决,在此总结一下引起该问题的原因 ...
- SQL查询语句 [2]
一.快捷查询 快捷查询方式是一种多字段查询的简化写法,在多个字段之间用'|'隔开表示OR,用'&'隔开表示 AND. 1.不同字段相同查询条件 在 Home/controller/UserC ...
- javascript使用setTimeout、setInterval时找不到变量的问题
我们在某个作用域内或者在自己定义的一个类里调用setTimeout.setInterval会经常会遇到找不到某个变量的错误. 比如下面这个例子: window.onload = function(){ ...
- Python 网络爬虫 002 (入门) 爬取一个网站之前,要了解的知识
网站站点的背景调研 1. 检查 robots.txt 网站都会定义robots.txt 文件,这个文件就是给 网络爬虫 来了解爬取该网站时存在哪些限制.当然了,这个限制仅仅只是一个建议,你可以遵守,也 ...