利用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 ...
随机推荐
- noip2017D2T3的几种写法...(BIT/线段树/平衡树)
题意各大oj上都有啦..想必来搜题解的都看过题面了...Qw Solution1: 首先观察n=1的情况,显然就是中间删掉一个数后面加上一个数,并查询那个删掉的数(以后把这样一个过程称为一个操作啦(( ...
- 【新手向】Centos系统文件权限的系统阐述与演示
在linux服务器日常管理中,我们会经常管理查看文件或者文件夹的权限内容以保证服务的正常运行.今天就和大家聊聊文件权限的那些事. 查看文件的权限情况可以用 ll 命令例: ll -d /kid #查看 ...
- 安装 MongoDB。
1.安装 MongoDB. 1.为软件包管理系统导入公钥. Ubuntu 软件包管理工具为了保证软件包的一致性和可靠性需要用 GPG 密钥检验软件包.使用下列命令导入 MongoDB 的 GPG 密钥 ...
- XE Button Color
XE Button Color,FMX Button 颜色 也可以放个rectangle+Glyph控件. http://blogs.embarcadero.com/sarinadupont/2014 ...
- c#.net常用字符串函数 字符串常用方法 string
RegionsStr = RegionsStr.Remove(RegionsStr.LastIndexOf(","), 1); //去掉最后一个逗号 string html = ...
- TypeError: 'append' called on an object that does not implement interface FormData 解决方法
使用ajax提交form表单时,$("formId").serialize()不能提交type="file"类型的input,这个时候可以选择使用FormDat ...
- mybaits中date类型显示时分秒(orcle数据库)
<insert id="insert" parameterType="daSysLoginLog"> insert into DA_SYS_LOGI ...
- adb pull 和 adb push
1. 操作单个文件 通过adb push,则可将文件添加到SD卡中.如果想在push的时候修改文件名称的话,只需要修改push的第二个参数改成完整路径(目录+文件名),如/sdcard/test-0. ...
- (转载)Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderListener
转载自:http://www.cnblogs.com/love540376/p/5527757.html Eclipse中tomcat部署工程启动后报错: 严重: Error configuring ...
- Action层, Service层 和 Dao层的功能区分
Action/Service/DAO简介: Action是管理业务(Service)调度和管理跳转的. Service是管理具体的功能的. Action只负责管理,而Service负责实施. DAO ...