SnowflakeIdUtil.java 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. package cn.efunbox.base.util;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5. * Twitter_Snowflake<br>
  6. * SnowFlake的结构如下(每部分用-分开):<br>
  7. * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
  8. * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
  9. * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
  10. * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
  11. * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
  12. * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
  13. * 加起来刚好64位,为一个Long型。<br>
  14. * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
  15. */
  16. public class SnowflakeIdUtil {
  17. private static volatile SnowflakeIdUtil singleton = null;
  18. // ==============================Fields===========================================
  19. /** 开始时间截 (2015-01-01) */
  20. private final long twepoch = 1420041600000L;
  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=1L;
  41. /** 数据中心ID(0~31) */
  42. private long datacenterId=1L;
  43. /** 毫秒内序列(0~4095) */
  44. private long sequence = 0L;
  45. /** 上次生成ID的时间截 */
  46. private long lastTimestamp = -1L;
  47. //==============================Constructors=====================================
  48. private SnowflakeIdUtil(){}
  49. /**
  50. * 构造函数
  51. */
  52. public static SnowflakeIdUtil getSnowflakeIdUtil(){
  53. if(singleton == null){
  54. synchronized (SnowflakeIdUtil.class){
  55. if(singleton == null){
  56. singleton = new SnowflakeIdUtil(0,0);
  57. }
  58. }
  59. }
  60. return singleton;
  61. }
  62. public static SnowflakeIdUtil getSnowflakeIdUtil(long workerId, long datacenterId){
  63. if(singleton == null){
  64. synchronized (SnowflakeIdUtil.class){
  65. if(singleton == null){
  66. singleton = new SnowflakeIdUtil(workerId,datacenterId);
  67. }
  68. }
  69. }
  70. return singleton;
  71. }
  72. /**
  73. * 构造函数
  74. * @param workerId 工作ID (0~31)
  75. * @param datacenterId 数据中心ID (0~31)
  76. */
  77. public SnowflakeIdUtil(long workerId, long datacenterId) {
  78. if (workerId > maxWorkerId || workerId < 0) {
  79. throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
  80. }
  81. if (datacenterId > maxDatacenterId || datacenterId < 0) {
  82. throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
  83. }
  84. this.workerId = workerId;
  85. this.datacenterId = datacenterId;
  86. }
  87. // ==============================Methods==========================================
  88. /**
  89. * 获得下一个ID (该方法是线程安全的)
  90. * @return SnowflakeId
  91. */
  92. public synchronized long nextId() {
  93. long timestamp = timeGen();
  94. //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
  95. if (timestamp < lastTimestamp) {
  96. throw new RuntimeException(
  97. String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
  98. }
  99. //如果是同一时间生成的,则进行毫秒内序列
  100. if (lastTimestamp == timestamp) {
  101. sequence = (sequence + 1) & sequenceMask;
  102. //毫秒内序列溢出
  103. if (sequence == 0) {
  104. //阻塞到下一个毫秒,获得新的时间戳
  105. timestamp = tilNextMillis(lastTimestamp);
  106. }
  107. }
  108. //时间戳改变,毫秒内序列重置
  109. else {
  110. sequence = 0L;
  111. }
  112. //上次生成ID的时间截
  113. lastTimestamp = timestamp;
  114. /* //移位并通过或运算拼到一起组成64位的ID
  115. return ((timestamp - twepoch) << timestampLeftShift) //
  116. | (datacenterId << datacenterIdShift) //
  117. | (workerId << workerIdShift) //
  118. | sequence;*/
  119. // modify by tomas 2017-08-28
  120. try {
  121. Thread.sleep(1);
  122. } catch (InterruptedException e) {
  123. e.printStackTrace();
  124. }
  125. return Long.parseLong(timestamp+ getNewAppend() );
  126. }
  127. protected String getNewAppend() {
  128. StringBuilder stringBuilder=new StringBuilder((System.nanoTime() + "").substring(7, 10));
  129. return stringBuilder.toString();
  130. }
  131. /**
  132. * 阻塞到下一个毫秒,直到获得新的时间戳
  133. * @param lastTimestamp 上次生成ID的时间截
  134. * @return 当前时间戳
  135. */
  136. protected long tilNextMillis(long lastTimestamp) {
  137. long timestamp = timeGen();
  138. while (timestamp <= lastTimestamp) {
  139. timestamp = timeGen();
  140. }
  141. return timestamp;
  142. }
  143. /**
  144. * 返回字符串类型 code
  145. * @return
  146. */
  147. public String nextCode() {
  148. return String.valueOf(nextId());
  149. }
  150. /**
  151. * 返回以毫秒为单位的当前时间
  152. * @return 当前时间(毫秒)
  153. */
  154. protected long timeGen() {
  155. return System.currentTimeMillis();
  156. }
  157. public static void main(String[] args) throws Exception{
  158. Set<Long> ids= new HashSet<>();
  159. long start=System.currentTimeMillis();
  160. for (int j=0 ;j<1000;j++){
  161. long id = SnowflakeIdUtil.getSnowflakeIdUtil().nextId();
  162. ids.add(id);
  163. //System.out.println(id);
  164. }
  165. System.out.println(ids.size()+"---time="+ (System.currentTimeMillis()-start));
  166. }
  167. }