利用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 ...
随机推荐
- redis学习二 排序
文章转载自:http://www.cnblogs.com/redcreen/archive/2011/02/15/1955226.html redis支持对list,set和sorted set元素的 ...
- Spring注解-TaskScheduler
一.定义配置类 import org.springframework.context.annotation.ComponentScan; import org.springframework.cont ...
- ubuntu 12.04 下 eclipse关联 source code
一.JDK source code 命令行中: sudo apt-get install openjdk-7-source 下好的jdk源码在 Linux 在目录 usr/lib/jvm/openjd ...
- Serializable 和 parcelable的实现和比较
首先这个两个接口都是用来序列化对象的 但是两者在性能和应用场合上有区别,parcelable的性能更好,但是在需要保存或者网络传输的时候需要选择Serializable因为parcelable版本在不 ...
- android task stack
http://www.android100.net/html/201402/22/5690.html
- [patl1-046]整除光棍
解题关键:模拟除法 #include<cstdio> #include<cstring> #include<algorithm> #include<cstdl ...
- Sequelize框架:
1.安装mysql支持: npm install mysql --save-dev 2.安装sequelize npm install sequelize --save-dev 3.创建ORM对象 v ...
- MySql 5.7中添加用户,新建数据库,用户授权,删除用户,修改密码
转自http://blog.csdn.net/w690333243/article/details/76576952 1.新建用户 创建test用户,密码是1234. MySQL -u root -p ...
- java内存模型和线程安全
- 自己实现 String 类
实现Stirng类:构造函数.复制构造.拷贝构造.重载<<符号(友元) #include <iostream> #include <string.h> #inclu ...