由于我们的数据库在生产环境中要分片部署(MyCat),所以我们不能使用数据库本
    身的自增功能来产生主键值,只能由程序来生成唯一的主键值。我们采用的是开源的
    twitter( 非官方中文惯称:推特.是国外的一个网站,是一个社交网络及微博客服务) 的
    snowflake (雪花)算法。
    图片.png
    默认情况下41bit的时间戳可以支持该算法使用到2082年,10bit的工作机器id可以
    支持1024台机器,序列号支持1毫秒产生4096个自增序列id . SnowFlake的优点是,整
    体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID
    作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右

    1. package util;
    2. import java.lang.management.ManagementFactory;
    3. import java.net.InetAddress;
    4. import java.net.NetworkInterface;
    5. /**
    6. * <p>名称:IdWorker.java</p>
    7. * <p>描述:分布式自增长ID</p>
    8. * <pre>
    9. * Twitter的 Snowflake JAVA实现方案
    10. * </pre>
    11. * 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用:
    12. * 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
    13. * 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,
    14. * 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识),
    15. * 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。
    16. * 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分),
    17. * 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。
    18. * <p>
    19. * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
    20. *
    21. * @author Polim
    22. */
    23. public class IdWorker {
    24. // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
    25. private final static long twepoch = 1288834974657L;
    26. // 机器标识位数
    27. private final static long workerIdBits = 5L;
    28. // 数据中心标识位数
    29. private final static long datacenterIdBits = 5L;
    30. // 机器ID最大值
    31. private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
    32. // 数据中心ID最大值
    33. private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    34. // 毫秒内自增位
    35. private final static long sequenceBits = 12L;
    36. // 机器ID偏左移12位
    37. private final static long workerIdShift = sequenceBits;
    38. // 数据中心ID左移17位
    39. private final static long datacenterIdShift = sequenceBits + workerIdBits;
    40. // 时间毫秒左移22位
    41. private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    42. private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
    43. /* 上次生产id时间戳 */
    44. private static long lastTimestamp = -1L;
    45. // 0,并发控制
    46. private long sequence = 0L;
    47. private final long workerId;
    48. // 数据标识id部分
    49. private final long datacenterId;
    50. public IdWorker(){
    51. this.datacenterId = getDatacenterId(maxDatacenterId);
    52. this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    53. }
    54. /**
    55. * @param workerId
    56. * 工作机器ID
    57. * @param datacenterId
    58. * 序列号
    59. */
    60. public IdWorker(long workerId, long datacenterId) {
    61. if (workerId > maxWorkerId || workerId < 0) {
    62. throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
    63. }
    64. if (datacenterId > maxDatacenterId || datacenterId < 0) {
    65. throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
    66. }
    67. this.workerId = workerId;
    68. this.datacenterId = datacenterId;
    69. }
    70. /**
    71. * 获取下一个ID
    72. *
    73. * @return
    74. */
    75. public synchronized long nextId() {
    76. long timestamp = timeGen();
    77. if (timestamp < lastTimestamp) {
    78. throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
    79. }
    80. if (lastTimestamp == timestamp) {
    81. // 当前毫秒内,则+1
    82. sequence = (sequence + 1) & sequenceMask;
    83. if (sequence == 0) {
    84. // 当前毫秒内计数满了,则等待下一秒
    85. timestamp = tilNextMillis(lastTimestamp);
    86. }
    87. } else {
    88. sequence = 0L;
    89. }
    90. lastTimestamp = timestamp;
    91. // ID偏移组合生成最终的ID,并返回ID
    92. long nextId = ((timestamp - twepoch) << timestampLeftShift)
    93. | (datacenterId << datacenterIdShift)
    94. | (workerId << workerIdShift) | sequence;
    95. return nextId;
    96. }
    97. private long tilNextMillis(final long lastTimestamp) {
    98. long timestamp = this.timeGen();
    99. while (timestamp <= lastTimestamp) {
    100. timestamp = this.timeGen();
    101. }
    102. return timestamp;
    103. }
    104. private long timeGen() {
    105. return System.currentTimeMillis();
    106. }
    107. /**
    108. * <p>
    109. * 获取 maxWorkerId
    110. * </p>
    111. */
    112. protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
    113. StringBuffer mpid = new StringBuffer();
    114. mpid.append(datacenterId);
    115. String name = ManagementFactory.getRuntimeMXBean().getName();
    116. if (!name.isEmpty()) {
    117. /*
    118. * GET jvmPid
    119. */
    120. mpid.append(name.split("@")[0]);
    121. }
    122. /*
    123. * MAC + PID 的 hashcode 获取16个低位
    124. */
    125. return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    126. }
    127. /**
    128. * <p>
    129. * 数据标识id部分
    130. * </p>
    131. */
    132. protected static long getDatacenterId(long maxDatacenterId) {
    133. long id = 0L;
    134. try {
    135. InetAddress ip = InetAddress.getLocalHost();
    136. NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    137. if (network == null) {
    138. id = 1L;
    139. } else {
    140. byte[] mac = network.getHardwareAddress();
    141. id = ((0x000000FF & (long) mac[mac.length - 1])
    142. | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
    143. id = id % (maxDatacenterId + 1);
    144. }
    145. } catch (Exception e) {
    146. System.out.println(" getDatacenterId: " + e.getMessage());
    147. }
    148. return id;
    149. }
    150. }