SnowflakeSequence.java 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package com.huimv.common.utils;
  2. import java.lang.management.ManagementFactory;
  3. import java.net.InetAddress;
  4. import java.net.NetworkInterface;
  5. /**
  6. * Twitter_Snowflake<br>
  7. * SnowFlake的结构如下(每部分用-分开):<br>
  8. * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
  9. * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
  10. * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
  11. * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
  12. * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
  13. * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
  14. * 加起来刚好64位,为一个Long型。<br>
  15. * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
  16. */
  17. public class SnowflakeSequence {
  18. // ==============================Fields===========================================
  19. /** 开始时间截 (2017/11/29 18:25:29) */
  20. private final long twepoch = 1511951129000L;
  21. /** 机器id所占的位数 */
  22. private final long workerIdBits = 5L;
  23. /** 数据标识id所占的位数 */
  24. private final long datacenterIdBits = 5L;
  25. /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
  26. private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
  27. /** 支持的最大数据标识id,结果是31 */
  28. private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
  29. /** 序列在id中占的位数 */
  30. private final long sequenceBits = 12L;
  31. /** 机器ID向左移12位 */
  32. private final long workerIdShift = sequenceBits;
  33. /** 数据标识id向左移17位(12+5) */
  34. private final long datacenterIdShift = sequenceBits + workerIdBits;
  35. /** 时间截向左移22位(5+5+12) */
  36. private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
  37. /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
  38. private final long sequenceMask = -1L ^ (-1L << sequenceBits);
  39. /** 工作机器ID(0~31) */
  40. private long workerId;
  41. /** 数据中心ID(0~31) */
  42. private long datacenterId;
  43. /** 毫秒内序列(0~4095) */
  44. private long sequence = 0L;
  45. /** 上次生成ID的时间截 */
  46. private long lastTimestamp = -1L;
  47. //==============================构造函数=====================================
  48. //根据mac地址产生datacenterid
  49. public SnowflakeSequence() {
  50. datacenterId = getDatacenterId(maxDatacenterId);
  51. workerId = getMaxWorkerId(datacenterId, maxWorkerId);
  52. // System.out.println("datacenterId:" + datacenterId + ",workerId:" + workerId);
  53. }
  54. /**
  55. * 构造函数
  56. * @param workerId 工作ID (0~31)
  57. * @param datacenterId 数据中心ID (0~31)
  58. */
  59. public SnowflakeSequence(long workerId, long datacenterId) {
  60. if (workerId > maxWorkerId || workerId < 0) {
  61. throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
  62. }
  63. if (datacenterId > maxDatacenterId || datacenterId < 0) {
  64. throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
  65. }
  66. this.workerId = workerId;
  67. this.datacenterId = datacenterId;
  68. }
  69. // ==============================Methods==========================================
  70. /**
  71. * 获得下一个ID (该方法是线程安全的)
  72. * @return SnowflakeId
  73. */
  74. public synchronized long nextId() {
  75. long timestamp = timeGen();
  76. //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
  77. if (timestamp < lastTimestamp) {
  78. throw new RuntimeException(
  79. String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
  80. }
  81. //如果是同一时间生成的,则进行毫秒内序列
  82. if (lastTimestamp == timestamp) {
  83. sequence = (sequence + 1) & sequenceMask;
  84. //毫秒内序列溢出
  85. if (sequence == 0) {
  86. //阻塞到下一个毫秒,获得新的时间戳
  87. timestamp = tilNextMillis(lastTimestamp);
  88. }
  89. }
  90. //时间戳改变,毫秒内序列重置
  91. else {
  92. sequence = 0L;
  93. }
  94. //上次生成ID的时间截
  95. lastTimestamp = timestamp;
  96. //移位并通过或运算拼到一起组成64位的ID
  97. return ((timestamp - twepoch) << timestampLeftShift) //
  98. | (datacenterId << datacenterIdShift) //
  99. | (workerId << workerIdShift) //
  100. | sequence;
  101. }
  102. /**
  103. * 阻塞到下一个毫秒,直到获得新的时间戳
  104. * @param lastTimestamp 上次生成ID的时间截
  105. * @return 当前时间戳
  106. */
  107. protected long tilNextMillis(long lastTimestamp) {
  108. long timestamp = timeGen();
  109. while (timestamp <= lastTimestamp) {
  110. timestamp = timeGen();
  111. }
  112. return timestamp;
  113. }
  114. /**
  115. * 返回以毫秒为单位的当前时间
  116. * @return 当前时间(毫秒)
  117. */
  118. protected long timeGen() {
  119. return System.currentTimeMillis();
  120. }
  121. /**
  122. * <p>
  123. * 数据标识id部分
  124. * </p>
  125. * @param maxDatacenterId
  126. * @return
  127. */
  128. protected static long getDatacenterId(long maxDatacenterId) {
  129. long id = 0L;
  130. try {
  131. InetAddress ip = InetAddress.getLocalHost();
  132. NetworkInterface network = NetworkInterface.getByInetAddress(ip);
  133. if (network == null) {
  134. id = 1L;
  135. } else {
  136. byte[] mac = network.getHardwareAddress();
  137. if (null != mac) {
  138. id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
  139. id = id % (maxDatacenterId + 1);
  140. }
  141. }
  142. } catch (Exception e) {
  143. System.err.println(" getDatacenterId: " + e.getMessage());
  144. }
  145. return id;
  146. }
  147. /**
  148. * 获取 maxWorkerId
  149. * @param datacenterId 数据中心id
  150. * @param maxWorkerId 机器id
  151. * @return maxWorkerId
  152. */
  153. protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
  154. StringBuilder mpid = new StringBuilder();
  155. mpid.append(datacenterId);
  156. String name = ManagementFactory.getRuntimeMXBean().getName();
  157. if (name != null && "".equals(name)) {
  158. // GET jvmPid
  159. mpid.append(name.split("@")[0]);
  160. }
  161. //MAC + PID 的 hashcode 获取16个低位
  162. return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
  163. }
  164. //==============================Test=============================================
  165. /** 测试 */
  166. public static void main(String[] args) {
  167. // SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
  168. SnowflakeSequence idWorker = new SnowflakeSequence();
  169. for (int i = 0; i < 10; i++) {
  170. long id = idWorker.nextId();
  171. // System.out.println(Long.toBinaryString(id));
  172. System.out.println(id);
  173. }
  174. }
  175. }