package com.shopping.test; import java.text.SimpleDateFormat; import java.util.Date; /***** * 雪花算法根據時間戳生成有序的 64 bit 的 Long 類型的唯一 ID * * 各 bit 含義: * 1 bit: 符號位,0 是正數 1 是負數, ID 為正數,所以恆取 0 * 41 bit: 時間差,我們可以選擇一個參考點,用它來計算與當前時間的時間差 (毫秒數),41 bit 存儲時間差,足夠使用 69 年 * 10 bit: 機器碼,能編碼 1024 台機器;可以手動指定含義,比如前5 bit 作為機器編號、后 5 bit 作為進程編號 * 12 bit: 序列號,同一機器同一毫秒內產生不同的序列號,12 bit 可以支持 4096 個序列號 * 優點: * 靈活配置:機器碼可以根據需求靈活配置含義 * 無需持久化:如果序號自增往往需要持久化,本算法不需要持久化 * ID 有含義/可逆性:ID 可以反解出來,對 ID 進行統計分析,可以很簡單的分析出整個系統的繁忙曲線,還可以定位到每個機器,在某段時間承擔了多少工作,分析出負載均衡情況 * 高性能:生成速度很快 * */ public class SnowflakeIdWorker { /** 開始時間截 (2019-08-21) */ private final long twepoch = 1566316801000L; /** 機器id所占的位數 */ private final long workerIdBits = 5L; /** 數據標識id所占的位數 */ private final long datacenterIdBits = 5L; /** 支持的最大機器id,結果是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位 */ private final long workerIdShift = sequenceBits; /** 數據標識id向左移17位(12+5) */ private final long datacenterIdShift = sequenceBits + workerIdBits; /** 時間截向左移22位(5+5+12) */ private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; /** 生成序列的掩碼,這里為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 SnowflakeIdWorker(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 (該方法是線程安全的) * @return SnowflakeId */ public synchronized long nextId() { long timestamp = timeGen(); //如果當前時間小於上一次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; //毫秒內序列溢出 if (sequence == 0) { //阻塞到下一個毫秒,獲得新的時間戳 timestamp = tilNextMillis(lastTimestamp); } } //時間戳改變,毫秒內序列重置 else { sequence = 0L; } //上次生成ID的時間截 lastTimestamp = timestamp; //移位並通過或運算拼到一起組成64位的ID return ((timestamp - twepoch) << timestampLeftShift) // | (datacenterId << datacenterIdShift) // | (workerId << workerIdShift) // | sequence; } /** * 阻塞到下一個毫秒,直到獲得新的時間戳 * @param lastTimestamp 上次生成ID的時間截 * @return 當前時間戳 */ protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 返回以毫秒為單位的當前時間 * @return 當前時間(毫秒) */ protected long timeGen() { return System.currentTimeMillis(); } /** 測試 */ public static void main(String[] args) { SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0); for (int i = 0; i < 1000; i++) { long id = idWorker.nextId(); //System.out.println(Long.toBinaryString(id)); System.out.println(id); } /*String s="2019-08-21 00:00:01"; long ts =0; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = simpleDateFormat.parse(s); ts = date.getTime(); }catch (Exception e){ ts =0; } System.out.println(ts);*/ } }