利用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; public class IdMaker { private ZkClient client = null;
private final String server;//记录服务器的地址
private final String root;//记录父节点的路径
private final String nodeName;//节点的名称
private volatile boolean running = false;
private ExecutorService cleanExector = null; //删除节点的级别
public enum RemoveMethod{
NONE,IMMEDIATELY,DELAY } public IdMaker(String zkServer,String root,String nodeName){ this.root = root;
this.server = zkServer;
this.nodeName = nodeName; } 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("127.0.0.1:2181",
"/NameService/IdGen", "ID");
idMaker.start(); try {
for (int i = ; i < ; i++) {
String id = idMaker.generateId(IdMaker.RemoveMethod.NONE);
System.out.println(id); }
} finally {
idMaker.stop(); }
}
}
利用zookeeper生成唯一id,通用性代码的更多相关文章
- 利用zookeeper生成唯一id
package com.cxy.com.cxy.curator; import java.util.concurrent.ExecutorService; import java.util.concu ...
- Java 利用 UUID 生成唯一性 ID 示例代码
用户ID首先生成,订单ID的生成可依赖用户ID. 下面代码前六位是日期,后八位是随机数,用于生成用户ID. public String getNewUserId() { String ipAddres ...
- PHP生成唯一ID的方法
PHP自带生成唯一id的函数:uniqid() 它是基于当前时间微秒数的 用法如下: echo uniqid(); //13位的字符串 echo uniqid("php_"); / ...
- PHP生成唯一ID
前言 PHP uniqid()函数可用于生成不重复的唯一标识符,该函数基于微秒级当前时间戳.在高并发或者间隔时长极短(如循环代码)的情况下,会出现大量重复数据.即使使用了第二个参数,也会重复,最好的方 ...
- 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(); ...
随机推荐
- ie6 ie7下报脚本错误"Expected identifier, string or number" 的原因和解决方法
在IE6和ie7里面,脚本报错"Expected identifier, string or number" 写下这个是个之前我已经很头疼了,因为我的代码在其他浏览器里都是正常的, ...
- nginx注册成服务
http://blog.csdn.net/t37240/article/details/51727563
- Tiny4412 Linux 内核配置流程
1.配置交叉编译器 默认情况下,内核构建的是与宿主机相同的体系架构镜像.如果要交叉编译,需要设置两个变量ARCH和CORSS_COMPILE. ①ARCH:指明目标体系架构,如x86.arm.mips ...
- 北京儿研所自制药一览表,宝妈们必读!<转>
原帖地址:http://www.360doc.com/content/15/0910/22/22655489_498339090.shtml
- [Python Study Notes]pynput实现对键盘控制与监控
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...
- android-auto-scroll-view-pager (无限广告轮播图)
github 地址: https://github.com/Trinea/android-auto-scroll-view-pager Gradle: compile ('cn.trinea.andr ...
- Python 网络爬虫 001 (科普) 网络爬虫简介
Python 网络爬虫 001 (科普) 网络爬虫简介 1. 网络爬虫是干什么的 我举几个生活中的例子: 例子一: 我平时会将 学到的知识 和 积累的经验 写成博客发送到CSDN博客网站上,那么对于我 ...
- 杭电ACM刷题(2):1005,Number Sequence 标签: 杭电acmC语言 2017-05-11 22:43 116人阅读
Problem Description A number sequence is defined as follows: f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1 ...
- Clos Network
1952年,Charles Clos 设计出了一种多级的交换架构,用多级的小型交换机阵列来构建一张大的无阻塞的网络.在此之前,要实现“无阻塞的架构”,只能采用NxN的Cross-bar方式. 而Clo ...
- 国内物联网平台(6):庆科云FogCloud
国内物联网平台(6)——庆科云FogCloud 马智 平台定位 FogCloud 快速接入智能硬件 FogCloud为开发者提供便捷的智能硬件接入服务,真正实现敏捷开发,快速迭代. FogCloud提 ...