1.配置类

  1. package io.renren.config;
  2. /**
  3. * @ClassName SnowflakeIdGenerator
  4. * @Date 上午 11:54
  5. */
  6. /**
  7. * 推特算法,雪花自增唯一id
  8. * @ClassName SnowflakeIdGenerator
  9. * @Author WHN
  10. */
  11. public class SnowflakeIdGenerator {
  12. //================================================Algorithm's Parameter=============================================
  13. // 系统开始时间截 (UTC 2021-02-03 12:00:00)(毫秒)
  14. private final long startTime = 1612324800000L;
  15. // 机器id所占的位数
  16. private final long workerIdBits = 5L;
  17. // 数据标识id所占的位数
  18. private final long dataCenterIdBits = 5L;
  19. // 支持的最大机器id(十进制),结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
  20. // -1L 左移 5位 (worker id 所占位数) 即 5位二进制所能获得的最大十进制数 - 31
  21. private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
  22. // 支持的最大数据标识id - 31
  23. private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);
  24. // 序列在id中占的位数
  25. private final long sequenceBits = 12L;
  26. // 机器ID 左移位数 - 12 (即末 sequence 所占用的位数)
  27. private final long workerIdMoveBits = sequenceBits;
  28. // 数据标识id 左移位数 - 17(12+5)
  29. private final long dataCenterIdMoveBits = sequenceBits + workerIdBits;
  30. // 时间截向 左移位数 - 22(5+5+12)
  31. private final long timestampMoveBits = sequenceBits + workerIdBits + dataCenterIdBits;
  32. // 生成序列的掩码(12位所对应的最大整数值),这里为4095 (0b111111111111=0xfff=4095)
  33. private final long sequenceMask = -1L ^ (-1L << sequenceBits);
  34. //=================================================Works's Parameter================================================
  35. /**
  36. * 工作机器ID(0~31)
  37. */
  38. private long workerId;
  39. /**
  40. * 数据中心ID(0~31)
  41. */
  42. private long dataCenterId;
  43. /**
  44. * 毫秒内序列(0~4095)
  45. */
  46. private long sequence = 0L;
  47. /**
  48. * 上次生成ID的时间截
  49. */
  50. private long lastTimestamp = -1L;
  51. //===============================================Constructors=======================================================
  52. /**
  53. * 构造函数
  54. *
  55. * @param workerId 工作ID (0~31)
  56. * @param dataCenterId 数据中心ID (0~31)
  57. */
  58. public SnowflakeIdGenerator(long workerId, long dataCenterId) {
  59. if (workerId > maxWorkerId || workerId < 0) {
  60. throw new IllegalArgumentException(String.format("Worker Id can't be greater than %d or less than 0", maxWorkerId));
  61. }
  62. if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
  63. throw new IllegalArgumentException(String.format("DataCenter Id can't be greater than %d or less than 0", maxDataCenterId));
  64. }
  65. this.workerId = workerId;
  66. this.dataCenterId = dataCenterId;
  67. }
  68. // ==================================================Methods========================================================
  69. // 线程安全的获得下一个 ID 的方法
  70. public synchronized long nextId() {
  71. long timestamp = currentTime();
  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. //毫秒内序列溢出 即 序列 > 4095
  81. if (sequence == 0) {
  82. //阻塞到下一个毫秒,获得新的时间戳
  83. timestamp = blockTillNextMillis(lastTimestamp);
  84. }
  85. }
  86. //时间戳改变,毫秒内序列重置
  87. else {
  88. sequence = 0L;
  89. }
  90. //上次生成ID的时间截
  91. lastTimestamp = timestamp;
  92. //移位并通过或运算拼到一起组成64位的ID
  93. return ((timestamp - startTime) << timestampMoveBits) //
  94. | (dataCenterId << dataCenterIdMoveBits) //
  95. | (workerId << workerIdMoveBits) //
  96. | sequence;
  97. }
  98. // 阻塞到下一个毫秒 即 直到获得新的时间戳
  99. protected long blockTillNextMillis(long lastTimestamp) {
  100. long timestamp = currentTime();
  101. while (timestamp <= lastTimestamp) {
  102. timestamp = currentTime();
  103. }
  104. return timestamp;
  105. }
  106. // 获得以毫秒为单位的当前时间
  107. protected long currentTime() {
  108. return System.currentTimeMillis();
  109. }
  110. //====================================================Test Case=====================================================
  111. /*public static void main(String[] args) {
  112. SnowflakeIdGenerator idWorker = new SnowflakeIdGenerator(0, 0);
  113. long id = idWorker.nextId();
  114. //System.out.println(Long.toBinaryString(id));
  115. System.out.println(id);
  116. }*/
  117. }

2.使用

  1. long nextId = idWorker.nextId();
  2. System.out.println(nextId);