|
1 | 1 | package com.jackson0714.passjava.common.utils; |
| 2 | + |
2 | 3 | /** |
3 | | - *@description TODO |
4 | | - *@author 悟空聊架构 |
5 | | - *@date 2022/11/15 13:42 |
6 | | - *@site www.passjava.cn |
7 | | - @github https://github.com/Jackson0714 |
8 | | - * |
9 | | -*/ |
10 | | -public class SnowFlakeUtilV2 { |
| 4 | + * @author 悟空聊架构 |
| 5 | + * @description TODO |
| 6 | + * @date 2022/11/15 13:42 |
| 7 | + * @site www.passjava.cn |
| 8 | + * @github https://github.com/Jackson0714 |
| 9 | + */ |
| 10 | +import java.net.NetworkInterface; |
| 11 | +import java.security.SecureRandom; |
| 12 | +import java.time.Instant; |
| 13 | +import java.util.Enumeration; |
| 14 | + |
| 15 | +/** |
| 16 | + * Distributed Sequence Generator. |
| 17 | + * Inspired by Twitter snowflake: https://github.com/twitter/snowflake/tree/snowflake-2010 |
| 18 | + * |
| 19 | + * This class should be used as a Singleton. |
| 20 | + * Make sure that you create and reuse a Single instance of Snowflake per node in your distributed system cluster. |
| 21 | + */ |
| 22 | +public class SnowflakeUtilV2 { |
| 23 | + private static final int UNUSED_BITS = 1; // Sign bit, Unused (always set to 0) |
| 24 | + private static final int EPOCH_BITS = 41; |
| 25 | + private static final int NODE_ID_BITS = 10; |
| 26 | + private static final int SEQUENCE_BITS = 12; |
| 27 | + |
| 28 | + private static final long maxNodeId = (1L << NODE_ID_BITS) - 1; |
| 29 | + private static final long maxSequence = (1L << SEQUENCE_BITS) - 1; |
| 30 | + |
| 31 | + // Custom Epoch (January 1, 2015 Midnight UTC = 2015-01-01T00:00:00Z) |
| 32 | + private static final long DEFAULT_CUSTOM_EPOCH = 1420070400000L; |
| 33 | + |
| 34 | + private final long nodeId; |
| 35 | + private final long customEpoch; |
| 36 | + |
| 37 | + private volatile long lastTimestamp = -1L; |
| 38 | + private volatile long sequence = 0L; |
| 39 | + |
| 40 | + // Create Snowflake with a nodeId and custom epoch |
| 41 | + // 初始化需要传入节点ID和年代 |
| 42 | + public SnowflakeUtilV2(long nodeId, long customEpoch) { |
| 43 | + if(nodeId < 0 || nodeId > maxNodeId) { |
| 44 | + throw new IllegalArgumentException(String.format("NodeId must be between %d and %d", 0, maxNodeId)); |
| 45 | + } |
| 46 | + this.nodeId = nodeId; |
| 47 | + this.customEpoch = customEpoch; |
| 48 | + } |
| 49 | + |
| 50 | + // Create Snowflake with a nodeId |
| 51 | + public SnowflakeUtilV2(long nodeId) { |
| 52 | + this(nodeId, DEFAULT_CUSTOM_EPOCH); |
| 53 | + } |
| 54 | + |
| 55 | + // Let Snowflake generate a nodeId |
| 56 | + public SnowflakeUtilV2() { |
| 57 | + this.nodeId = createNodeId(); |
| 58 | + this.customEpoch = DEFAULT_CUSTOM_EPOCH; |
| 59 | + } |
| 60 | + |
| 61 | + // 这个函数用于获取下一个ID |
| 62 | + public synchronized long nextId() { |
| 63 | + long currentTimestamp = timestamp(); |
| 64 | + |
| 65 | + if(currentTimestamp < lastTimestamp) { |
| 66 | + throw new IllegalStateException("Invalid System Clock!"); |
| 67 | + } |
| 68 | + |
| 69 | + // 同一个时间戳,我们需要递增序号 |
| 70 | + if (currentTimestamp == lastTimestamp) { |
| 71 | + sequence = (sequence + 1) & maxSequence; |
| 72 | + if(sequence == 0) { |
| 73 | + // 如果序号耗尽,则需要等待到下一秒继续执行 |
| 74 | + // Sequence Exhausted, wait till next millisecond. |
| 75 | + currentTimestamp = waitNextMillis(currentTimestamp); |
| 76 | + } |
| 77 | + } else { |
| 78 | + // reset sequence to start with zero for the next millisecond |
| 79 | + sequence = 0; |
| 80 | + } |
| 81 | + |
| 82 | + lastTimestamp = currentTimestamp; |
| 83 | + |
| 84 | + long id = currentTimestamp << (NODE_ID_BITS + SEQUENCE_BITS) |
| 85 | + | (nodeId << SEQUENCE_BITS) |
| 86 | + | sequence; |
| 87 | + |
| 88 | + return id; |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | + |
| 93 | + // Get current timestamp in milliseconds, adjust for the custom epoch. |
| 94 | + private long timestamp() { |
| 95 | + return Instant.now().toEpochMilli() - customEpoch; |
| 96 | + } |
| 97 | + |
| 98 | + // 由于这样被耗尽的情况不多,且需要等待的时间也只有1ms;所以我们选择死循环进行阻塞 |
| 99 | + // Block and wait till next millisecond |
| 100 | + private long waitNextMillis(long currentTimestamp) { |
| 101 | + while (currentTimestamp == lastTimestamp) { |
| 102 | + currentTimestamp = timestamp(); |
| 103 | + } |
| 104 | + return currentTimestamp; |
| 105 | + } |
| 106 | + |
| 107 | + // 默认基于mac地址生成节点ID |
| 108 | + private long createNodeId() { |
| 109 | + long nodeId; |
| 110 | + try { |
| 111 | + StringBuilder sb = new StringBuilder(); |
| 112 | + Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); |
| 113 | + while (networkInterfaces.hasMoreElements()) { |
| 114 | + NetworkInterface networkInterface = networkInterfaces.nextElement(); |
| 115 | + byte[] mac = networkInterface.getHardwareAddress(); |
| 116 | + if (mac != null) { |
| 117 | + for(byte macPort: mac) { |
| 118 | + sb.append(String.format("%02X", macPort)); |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + nodeId = sb.toString().hashCode(); |
| 123 | + } catch (Exception ex) { |
| 124 | + nodeId = (new SecureRandom().nextInt()); |
| 125 | + } |
| 126 | + nodeId = nodeId & maxNodeId; |
| 127 | + return nodeId; |
| 128 | + } |
| 129 | + |
| 130 | + public long[] parse(long id) { |
| 131 | + long maskNodeId = ((1L << NODE_ID_BITS) - 1) << SEQUENCE_BITS; |
| 132 | + long maskSequence = (1L << SEQUENCE_BITS) - 1; |
| 133 | + |
| 134 | + long timestamp = (id >> (NODE_ID_BITS + SEQUENCE_BITS)) + customEpoch; |
| 135 | + long nodeId = (id & maskNodeId) >> SEQUENCE_BITS; |
| 136 | + long sequence = id & maskSequence; |
| 137 | + |
| 138 | + return new long[]{timestamp, nodeId, sequence}; |
| 139 | + } |
| 140 | + |
| 141 | + @Override |
| 142 | + public String toString() { |
| 143 | + return "Snowflake Settings [EPOCH_BITS=" + EPOCH_BITS + ", NODE_ID_BITS=" + NODE_ID_BITS |
| 144 | + + ", SEQUENCE_BITS=" + SEQUENCE_BITS + ", CUSTOM_EPOCH=" + customEpoch |
| 145 | + + ", NodeId=" + nodeId + "]"; |
| 146 | + } |
11 | 147 | } |