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的更多相关文章

  1. 利用zookeeper生成唯一id,通用性代码

    在上篇中是写死的,这章就写出通用的 package com.cxy.com.cxy.curator; import java.util.concurrent.ExecutorService; impo ...

  2. PHP生成唯一ID的方法

    PHP自带生成唯一id的函数:uniqid() 它是基于当前时间微秒数的 用法如下: echo uniqid(); //13位的字符串 echo uniqid("php_"); / ...

  3. php 生成唯一id的几种解决方法

    php 生成唯一id的几种解决方法   网上查了下,有很多的方法 1.md5(time() . mt_rand(1,1000000)); 这种方法有一定的概率会出现重复 2.php内置函数uniqid ...

  4. PHP使用SnowFlake算法生成唯一ID

    前言:最近需要做一套CMS系统,由于功能比较单一,而且要求灵活,所以放弃了WP这样的成熟系统,自己做一套相对简单一点的.文章的详情页URL想要做成url伪静态的格式即xxx.html 其中xxx考虑过 ...

  5. php生成唯一id/唯一标识符/唯一订单号

    /** * php 生成唯一id * https://blog.csdn.net/hzqghost/article/details/18914681 */ function guid($factor= ...

  6. 如何使用php生成唯一ID的4种方法

    php生成唯一ID的应用场景非常普遍,如临时缓存文件名称,临时变量,临时安全码等,uniqid()函数基于以微秒计的当前时间,生成一个唯一的 ID.由于生成唯一ID与微秒时间关联,因此ID的唯一性非常 ...

  7. PHP获取时间戳和微秒数以及生成唯一ID

    microtime函数 描述:返回当前Unix时间戳和微秒数 语法:mixed microtime( [ bool $get_as_float ] ) //直接输出 echo microtime(); ...

  8. 根据twitter的snowflake算法生成唯一ID

    C#版本 /// <summary> /// 根据twitter的snowflake算法生成唯一ID /// snowflake算法 64 位 /// 0---0000000000 000 ...

  9. C# 根据twitter的snowflake算法生成唯一ID

    C# 版算法: using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...

随机推荐

  1. RPC: program not registered (ZT)

    When we trying to use a particular RPC  program, below may indicate that rpcbind is not running or t ...

  2. #调整随机森林的参数(调整n_estimators随机森林中树的数量默认10个树,精度递增显著,但并不是越多越好),加上verbose=True,显示进程使用信息

    #调整随机森林的参数(调整n_estimators随机森林中树的数量默认10个树,精度递增显著) from sklearn import datasets X, y = datasets.make_c ...

  3. spring各版本下载地址

    发现从spring.io里面找下载连接不好找了,但是机智的我还是找到了,这里做下分享 一.纯spring http://repo.spring.io/release/org/springframewo ...

  4. JAVA之数组队列

    package xxj.datastructure0810; import java.util.Random; public class DataStructure { /** * @param ar ...

  5. C/C++下测量函数运行时间

    C/C++下测量函数运行时间 time.h介绍 C/C++中的计时函数是clock(),而与其相关的数据类型是clock_t. clock_t clock( void ); 这个函数返回从" ...

  6. [Python Study Notes]计算器

    # ------------------------------------------------------------------------------------- # @文件: 计算器.p ...

  7. import requests

  8. JS/jQuery--iframe框架内外元素的操作(转)

    JS/jQuery--iframe框架内外元素的操作 原创 2017年12月07日 14:23:09 标签: js / iframe 28 两个问题: 如何在父页面操作iframe框架内的元素? 如何 ...

  9. Web性能优化 高并发网站解决 单例 已看1

    Web性能优化分为服务器端和浏览器端两个方面. 一.浏览器端,关于浏览器端优化,分很多个方面1.压缩源码和图片JavaScript文件源代码可以采用混淆压缩的方式,CSS文件源代码进行普通压缩,JPG ...

  10. MarkdownPad 2 安装和破解

    MarkdownPad 2 安装和破解 下载:http://markdownpad.com/ 下载下面这个: 破解:http://w3cboy.com/post/2014/10/MarkdownPad ...