image.png

    1. public class IdWorker {
    2. // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
    3. private final static long twepoch = 1288834974657L;
    4. // 机器标识位数
    5. private final static long workerIdBits = 5L;
    6. // 数据中心标识位数
    7. private final static long datacenterIdBits = 5L;
    8. // 机器ID最大值
    9. private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
    10. // 数据中心ID最大值
    11. private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    12. // 毫秒内自增位
    13. private final static long sequenceBits = 12L;
    14. // 机器ID偏左移12位
    15. private final static long workerIdShift = sequenceBits;
    16. // 数据中心ID左移17位
    17. private final static long datacenterIdShift = sequenceBits + workerIdBits;
    18. // 时间毫秒左移22位
    19. private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    20. private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
    21. /* 上次生产id时间戳 */
    22. private static long lastTimestamp = -1L;
    23. //同毫秒并发控制
    24. private long sequence = 0L;
    25. //机器ID
    26. private final long workerId;
    27. //机房ID
    28. private final long datacenterId;
    29. public IdWorker(){
    30. this.datacenterId = getDatacenterId(maxDatacenterId);
    31. this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    32. }
    33. /**
    34. * @param workerId
    35. * 工作机器ID
    36. * @param datacenterId
    37. * 序列号
    38. */
    39. public IdWorker(long workerId, long datacenterId) {
    40. if (workerId > maxWorkerId || workerId < 0) {
    41. throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
    42. }
    43. if (datacenterId > maxDatacenterId || datacenterId < 0) {
    44. throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
    45. }
    46. this.workerId = workerId;
    47. this.datacenterId = datacenterId;
    48. }
    49. /**
    50. * 获取下一个ID
    51. *
    52. * @return
    53. */
    54. public synchronized long nextId() {
    55. long timestamp = timeGen();
    56. if (timestamp < lastTimestamp) {
    57. throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
    58. }
    59. if (lastTimestamp == timestamp) {
    60. // 当前毫秒内,则+1
    61. sequence = (sequence + 1) & sequenceMask;
    62. if (sequence == 0) {
    63. // 当前毫秒内计数满了,则等待下一秒
    64. timestamp = tilNextMillis(lastTimestamp);
    65. }
    66. } else {
    67. sequence = 0L;
    68. }
    69. lastTimestamp = timestamp;
    70. // ID偏移组合生成最终的ID,并返回ID
    71. long nextId = ((timestamp - twepoch) << timestampLeftShift)
    72. | (datacenterId << datacenterIdShift)
    73. | (workerId << workerIdShift) | sequence;
    74. return nextId;
    75. }
    76. private long tilNextMillis(final long lastTimestamp) {
    77. long timestamp = this.timeGen();
    78. while (timestamp <= lastTimestamp) {
    79. timestamp = this.timeGen();
    80. }
    81. return timestamp;
    82. }
    83. private long timeGen() {
    84. return System.currentTimeMillis();
    85. }
    86. /**
    87. * <p>
    88. * 获取 maxWorkerId
    89. * </p>
    90. */
    91. protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
    92. StringBuffer mpid = new StringBuffer();
    93. mpid.append(datacenterId);
    94. String name = ManagementFactory.getRuntimeMXBean().getName();
    95. if (!name.isEmpty()) {
    96. /*
    97. * GET jvmPid
    98. */
    99. mpid.append(name.split("@")[0]);
    100. }
    101. /*
    102. * MAC + PID 的 hashcode 获取16个低位
    103. */
    104. return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    105. }
    106. /**
    107. * <p>
    108. * 数据标识id部分
    109. * </p>
    110. */
    111. protected static long getDatacenterId(long maxDatacenterId) {
    112. long id = 0L;
    113. try {
    114. InetAddress ip = InetAddress.getLocalHost();
    115. NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    116. if (network == null) {
    117. id = 1L;
    118. } else {
    119. byte[] mac = network.getHardwareAddress();
    120. id = ((0x000000FF & (long) mac[mac.length - 1])
    121. | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
    122. id = id % (maxDatacenterId + 1);
    123. }
    124. } catch (Exception e) {
    125. System.out.println(" getDatacenterId: " + e.getMessage());
    126. }
    127. return id;
    128. }
    129. }