public class SnowKeyGen { //開始時間 private final long startTime = 1498608000000L; //機器ID所佔大小 private final long workerIdBits = 5L; // 數據標識id所佔的位數 private final long dataCenterIdBits = 5L; // 支持的最大機器id(十進制),結果是31 (這個移位算法能夠很快的計算出幾位二進制數所能表示的最大十進制數) // -1L 左移 5位 (worker id 所佔位數) 即 5位二進制所能得到的最大十進制數 - 31 private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 支持的最大數據標識id - 31 private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits); // 序列在id中佔的位數 private final long sequenceBits = 12L; // 機器ID 左移位數 - 12 (即末 sequence 所佔用的位數) private final long workerIdMoveBits = sequenceBits; // 數據標識id 左移位數 - 17(12+5) private final long dataCenterIdMoveBits = sequenceBits + workerIdBits; // 時間截向 左移位數 - 22(5+5+12) private final long timestampMoveBits = sequenceBits + workerIdBits + dataCenterIdBits; // 生成序列的掩碼(12位所對應的最大整數值),這裏爲4095 (0b111111111111=0xfff=4095) private final long sequenceMask = -1L ^ (-1L << sequenceBits); /** * 工做機器ID(0~31) */ private long workerId; /** * 數據中心ID(0~31) */ private long dataCenterId; /** * 毫秒內序列(0~4095) */ private long sequence = 0L; /** * 上次生成ID的時間截 */ private long lastTimestamp = -1L; /** * 構造函數 * * @param workerId 工做ID (0~31) * @param dataCenterId 數據中心ID (0~31) */ public SnowKeyGen(long workerId, long dataCenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("Worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (dataCenterId > maxDataCenterId || dataCenterId < 0) { throw new IllegalArgumentException(String.format("DataCenter Id can't be greater than %d or less than 0", maxDataCenterId)); } this.workerId = workerId; this.dataCenterId = dataCenterId; } // 線程安全的得到下一個 ID 的方法 public synchronized long nextId() { long timestamp = currentTime(); //若是當前時間小於上一次ID生成的時間戳: 說明系統時鐘回退過 - 這個時候應當拋出異常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //若是是同一時間生成的,則進行毫秒內序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; //毫秒內序列溢出 即 序列 > 4095 if (sequence == 0) { //阻塞到下一個毫秒,得到新的時間戳 timestamp = blockTillNextMillis(lastTimestamp); } } //時間戳改變,毫秒內序列重置 else { sequence = 0L; } //上次生成ID的時間截 lastTimestamp = timestamp; //移位並經過或運算拼到一塊兒組成64位的ID return ((timestamp - startTime) << timestampMoveBits) // | (dataCenterId << dataCenterIdMoveBits) // | (workerId << workerIdMoveBits) // | sequence; } // 阻塞到下一個毫秒 即 直到得到新的時間戳 private long blockTillNextMillis(long lastTimestamp) { long timestamp = currentTime(); while (timestamp <= lastTimestamp) { timestamp = currentTime(); } return timestamp; } // 得到以毫秒爲單位的當前時間 private long currentTime() { return System.currentTimeMillis(); } public static void main(String[] args) { SnowKeyGen idWorker = new SnowKeyGen(0, 0); for (int i = 0; i < 1000; i++) { long id = idWorker.nextId(); System.out.println(Long.toBinaryString(id)); System.out.println(id); } } }