集群节点全局ID生成器

我们在开发中,有时非常需要一个全局唯一的ID值,不管是业务需求,还是为了以后可能的分表需求,全局唯一值都非常有用,本篇大象就来讲讲这个实现并对ID生成器性能进行一下测试。
    大象所讲的这个全局唯一ID生成器,其实是Twitter公开的一个算法,源码是用Scala写的,被国内的开源爱好者改写成了Java版本。
    大象将这个类的调用简化了一下,实际使用中还是应该根据机器节点和数据中心节点来配置相关的参数。我这里假设只有一个节点作为ID号的生成器,所以workerId和datacenterId都设为0,当前时间与计算标记时间twepoch(Thu, 04 Nov 2010 01:42:54 GMT)之间的毫秒数是一个38位长度的long值,再左移timestampLeftShift(22位),就得到一个60位长度的long数字,该数字与datacenterId << datacenterIdShift取或,datacenterId最小值为0,最大值为31,所以长度为1-5位,datacenterIdShift是17位,所以结果就是最小值为0,最大值为22位长度的long,同理,workerId << workerIdShift的最大值为17位的long。所以最终生成的会是一个60位长度的long型唯一ID下载

   

 

Java代码    收藏代码
  1. /** 
  2.  * 全局唯一ID生成器 
  3.  */  
  4. public class IdGen {  
  5.   
  6.     private long workerId;  
  7.     private long datacenterId;  
  8.     private long sequence = 0L;  
  9.     private long twepoch = 1288834974657L; //Thu, 04 Nov 2010 01:42:54 GMT  
  10.     private long workerIdBits = 5L; //节点ID长度  
  11.     private long datacenterIdBits = 5L; //数据中心ID长度  
  12.     private long maxWorkerId = -1L ^ (-1L << workerIdBits); //最大支持机器节点数0~31,一共32个  
  13.     private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); //最大支持数据中心节点数0~31,一共32个  
  14.     private long sequenceBits = 12L; //序列号12位  
  15.     private long workerIdShift = sequenceBits; //机器节点左移12位  
  16.     private long datacenterIdShift = sequenceBits + workerIdBits; //数据中心节点左移17位  
  17.     private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; //时间毫秒数左移22位  
  18.     private long sequenceMask = -1L ^ (-1L << sequenceBits); //4095  
  19.      private long lastTimestamp = -1L;  
  20.       
  21.     private static class IdGenHolder {  
  22.         private static final IdGen instance = new IdGen();  
  23.     }  
  24.       
  25.     public static IdGen get(){  
  26.         return IdGenHolder.instance;  
  27.     }  
  28.   
  29.     public IdGen() {  
  30.         this(0L, 0L);  
  31.     }  
  32.   
  33.     public IdGen(long workerId, long datacenterId) {  
  34.         if (workerId > maxWorkerId || workerId < 0) {  
  35.             throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));  
  36.         }  
  37.         if (datacenterId > maxDatacenterId || datacenterId < 0) {  
  38.             throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));  
  39.         }  
  40.         this.workerId = workerId;  
  41.         this.datacenterId = datacenterId;  
  42.     }  
  43.       
  44.     public synchronized long nextId() {  
  45.         long timestamp = timeGen(); //获取当前毫秒数  
  46.         //如果服务器时间有问题(时钟后退) 报错。  
  47.         if (timestamp < lastTimestamp) {  
  48.             throw new RuntimeException(String.format(  
  49.                     "Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));  
  50.         }  
  51.         //如果上次生成时间和当前时间相同,在同一毫秒内  
  52.         if (lastTimestamp == timestamp) {  
  53.             //sequence自增,因为sequence只有12bit,所以和sequenceMask相与一下,去掉高位  
  54.             sequence = (sequence + 1) & sequenceMask;  
  55.             //判断是否溢出,也就是每毫秒内超过4095,当为4096时,与sequenceMask相与,sequence就等于0  
  56.             if (sequence == 0) {  
  57.                 timestamp = tilNextMillis(lastTimestamp); //自旋等待到下一毫秒  
  58.             }  
  59.         } else {  下载
  60.             sequence = 0L; //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加  
  61.         }  
  62.         lastTimestamp = timestamp;  
  63.         // 最后按照规则拼出ID。  
  64.         // 000000000000000000000000000000000000000000  00000            00000       000000000000  
  65. // time                                                               datacenterId   workerId    sequence  
  66.          return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift)  
  67.                 | (workerId << workerIdShift) | sequence;  
  68.     }  
  69.   
  70.     protected long tilNextMillis(long lastTimestamp) {  
  71.         long timestamp = timeGen();  
  72.         while (timestamp <= lastTimestamp) {  
  73.             timestamp = timeGen();  
  74.         }  
  75.         return timestamp;  
  76.     }  
  77.   
  78.     protected long timeGen() {  
  79.         return System.currentTimeMillis();  
  80.     }  
  81. }  

 

 

    接下来我再写个测试类,看下并发情况下,1秒钟可以生成多少个ID。我测试用的电脑CPU为I5-4210U,内存8G,JDK为1.7.0_79,系统是64位WIN 7,使用-server模式下载

 

Java代码    收藏代码
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.TimeUnit;  
  7.   
  8. import org.junit.Test;  
  9.   
  10. public class GeneratorTest {  
  11.   
  12.     @Test  
  13.     public void testIdGenerator() {  
  14.         long avg = 0;  
  15.         for (int k = 0; k < 10; k++) {  
  16.             List<Callable<Long>> partitions = new ArrayList<Callable<Long>>();  
  17.             final IdGen idGen = IdGen.get();  
  18.             for (int i = 0; i < 1400000; i++) {  
  19.                 partitions.add(new Callable<Long>() {  
  20.                     @Override  
  21.                     public Long call() throws Exception {  
  22.                         return idGen.nextId();  
  23.                     }  
  24.                 });  
  25.             }  
  26.             ExecutorService executorPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());  
  27.             try {  
  28.                 long s = System.currentTimeMillis();  
  29.                 executorPool.invokeAll(partitions, 10000, TimeUnit.SECONDS);  
  30.                 long s_avg = System.currentTimeMillis() - s;  
  31.                 avg += s_avg;  
  32.                 System.out.println("完成时间需要: " + s_avg / 1.0e3 + "秒");  
  33.                 executorPool.shutdown();  
  34.             } catch (Exception e) {  
  35.                 e.printStackTrace();  
  36.             }  
  37.         }  
  38.         System.out.println("平均完成时间需要: " + avg / 10 / 1.0e3 + "秒");  
  39.     }  
  40. }  

 


    运行10次,平均下来,每次1.038秒生成140万个ID,除了第1次时间在3秒左右和第2次1.6秒左右,其余8次都在0.7秒左右。如果使用更好的硬件,测试数据肯定会更好。因此从大的方向上看,单节点的ID生成器基本上可以满足我们的需要了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值