SnowflakeIdUtils.java 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package com.primeton.damp.utils;
  2. import org.apache.commons.lang3.RandomUtils;
  3. import org.apache.commons.lang3.StringUtils;
  4. import java.net.Inet4Address;
  5. import java.net.UnknownHostException;
  6. /**
  7. * Twitter_Snowflake<br>
  8. * SnowFlake的结构如下(每部分用-分开):<br>
  9. * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
  10. * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
  11. * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
  12. * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
  13. * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
  14. * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
  15. * 加起来刚好64位,为一个Long型。<br>
  16. * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
  17. */
  18. public class SnowflakeIdUtils {
  19. // ==============================Fields===========================================
  20. /** 开始时间截 (2015-01-01) */
  21. private final long twepoch = 1489111610226L;
  22. /** 机器id所占的位数 */
  23. private final long workerIdBits = 5L;
  24. /** 数据标识id所占的位数 */
  25. private final long dataCenterIdBits = 5L;
  26. /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
  27. private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
  28. /** 支持的最大数据标识id,结果是31 */
  29. private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);
  30. /** 序列在id中占的位数 */
  31. private final long sequenceBits = 12L;
  32. /** 机器ID向左移12位 */
  33. private final long workerIdShift = sequenceBits;
  34. /** 数据标识id向左移17位(12+5) */
  35. private final long dataCenterIdShift = sequenceBits + workerIdBits;
  36. /** 时间截向左移22位(5+5+12) */
  37. private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
  38. /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
  39. private final long sequenceMask = -1L ^ (-1L << sequenceBits);
  40. /** 工作机器ID(0~31) */
  41. private long workerId;
  42. /** 数据中心ID(0~31) */
  43. private long dataCenterId;
  44. /** 毫秒内序列(0~4095) */
  45. private long sequence = 0L;
  46. /** 上次生成ID的时间截 */
  47. private long lastTimestamp = -1L;
  48. private static SnowflakeIdUtils idWorker = new SnowflakeIdUtils(getWorkId(), getDataCenterId());
  49. //==============================Constructors=====================================
  50. /**
  51. * 构造函数
  52. * @param workerId 工作ID (0~31)
  53. * @param dataCenterId 数据中心ID (0~31)
  54. */
  55. private SnowflakeIdUtils(long workerId, long dataCenterId) {
  56. if (workerId > maxWorkerId || workerId < 0) {
  57. throw new IllegalArgumentException(String.format("workerId can't be greater than %d or less than 0", maxWorkerId));
  58. }
  59. if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
  60. throw new IllegalArgumentException(String.format("dataCenterId can't be greater than %d or less than 0", maxDataCenterId));
  61. }
  62. this.workerId = workerId;
  63. this.dataCenterId = dataCenterId;
  64. }
  65. // ==============================Methods==========================================
  66. /**
  67. * 获得下一个ID (该方法是线程安全的)
  68. * @return SnowflakeId
  69. */
  70. public synchronized long nextId() {
  71. long timestamp = timeGen();
  72. //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
  73. if (timestamp < lastTimestamp) {
  74. throw new RuntimeException(
  75. String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
  76. }
  77. //如果是同一时间生成的,则进行毫秒内序列
  78. if (lastTimestamp == timestamp) {
  79. sequence = (sequence + 1) & sequenceMask;
  80. //毫秒内序列溢出
  81. if (sequence == 0) {
  82. //阻塞到下一个毫秒,获得新的时间戳
  83. timestamp = tilNextMillis(lastTimestamp);
  84. }
  85. }
  86. //时间戳改变,毫秒内序列重置
  87. else {
  88. sequence = 0L;
  89. }
  90. //上次生成ID的时间截
  91. lastTimestamp = timestamp;
  92. //移位并通过或运算拼到一起组成64位的ID
  93. return ((timestamp - twepoch) << timestampLeftShift)
  94. | (dataCenterId << dataCenterIdShift)
  95. | (workerId << workerIdShift)
  96. | sequence;
  97. }
  98. /**
  99. * 阻塞到下一个毫秒,直到获得新的时间戳
  100. * @param lastTimestamp 上次生成ID的时间截
  101. * @return 当前时间戳
  102. */
  103. protected long tilNextMillis(long lastTimestamp) {
  104. long timestamp = timeGen();
  105. while (timestamp <= lastTimestamp) {
  106. timestamp = timeGen();
  107. }
  108. return timestamp;
  109. }
  110. /**
  111. * 返回以毫秒为单位的当前时间
  112. * @return 当前时间(毫秒)
  113. */
  114. protected long timeGen() {
  115. return System.currentTimeMillis();
  116. }
  117. private static Long getWorkId(){
  118. try {
  119. String hostAddress = Inet4Address.getLocalHost().getHostAddress();
  120. int[] ints = StringUtils.toCodePoints(hostAddress);
  121. int sums = 0;
  122. for(int b : ints){
  123. sums += b;
  124. }
  125. return (long)(sums % 32);
  126. } catch (UnknownHostException e) {
  127. // 如果获取失败,则使用随机数备用
  128. return RandomUtils.nextLong(0,31);
  129. }
  130. }
  131. private static Long getDataCenterId(){
  132. int[] ints = StringUtils.toCodePoints(NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
  133. int sums = 0;
  134. for (int i : ints) {
  135. sums += i;
  136. }
  137. return (long)(sums % 32);
  138. }
  139. /**
  140. * 静态工具类
  141. *
  142. * @return
  143. */
  144. public static Long generateId(){
  145. return idWorker.nextId();
  146. }
  147. //==============================Test=============================================
  148. /** 测试 */
  149. public static void main(String[] args) {
  150. System.out.println(System.currentTimeMillis());
  151. long startTime = System.nanoTime();
  152. for (int i = 0; i < 50000; i++) {
  153. long id = SnowflakeIdUtils.generateId();
  154. System.out.println(id);
  155. }
  156. System.out.println((System.nanoTime()-startTime)/1000000+"ms");
  157. }
  158. }