雪花算法 Java 版


雪花算法根據時間戳生成有序的 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 Snowflake {

    /**
     * 每一部分所占位數
     */
    private final long unusedBits = 1L;
    private final long timestampBits = 41L;
    private final long datacenterIdBits = 5L;
    private final long workerIdBits = 5L;
    private final long sequenceBits = 12L;

    /**
     * 向左的位移
     */
    private final long timestampShift = sequenceBits + datacenterIdBits + workerIdBits;
    private final long datacenterIdShift = sequenceBits + workerIdBits;
    private final long workerIdShift = sequenceBits;

    /**
     * 起始時間戳,初始化后不可修改
     */
    private final long epoch = 1451606400000L; // 2016-01-01

    /**
     * 數據中心編碼,初始化后不可修改
     * 最大值: 2^5-1 取值范圍: [0,31]
     */
    private final long datacenterId;

    /**
     * 機器或進程編碼,初始化后不可修改
     * 最大值: 2^5-1 取值范圍: [0,31]
     */
    private final long workerId;

    /**
     * 序列號
     * 最大值: 2^12-1 取值范圍: [0,4095]
     */
    private long sequence = 0L;

    /** 上次執行生成 ID 方法的時間戳 */
    private long lastTimestamp = -1L;

    /*
     * 每一部分最大值
     */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 2^5-1
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 2^5-1
    private final long maxSequence = -1L ^ (-1L << sequenceBits); // 2^12-1

    /**
     * 生成序列號
     */
    public synchronized long nextId() {
        long currTimestamp = timestampGen();

        if (currTimestamp < lastTimestamp) {
            throw new IllegalStateException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
                            lastTimestamp - currTimestamp));
        }

        if (currTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & maxSequence;
            if (sequence == 0) { // overflow: greater than max sequence
                currTimestamp = waitNextMillis(currTimestamp);
            }

        } else { // reset to 0 for next period/millisecond
            sequence = 0L;
        }

        // track and memo the time stamp last snowflake ID generated
        lastTimestamp = currTimestamp;

        return ((currTimestamp - epoch) << timestampShift) | //
                (datacenterId << datacenterIdShift) | //
                (workerId << workerIdShift) | // new line for nice looking
                sequence;
    }

    public Snowflake(long datacenterId, long workerId) {
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }

        this.datacenterId = datacenterId;
        this.workerId = workerId;
    }

    /**
     * 追蹤調用 waitNextMillis 方法的次數
     */
    private final AtomicLong waitCount = new AtomicLong(0);

    public long getWaitCount() {
        return waitCount.get();
    }

    /**
     * 循環阻塞直到下一秒
     */
    protected long waitNextMillis(long currTimestamp) {
        waitCount.incrementAndGet();
        while (currTimestamp <= lastTimestamp) {
            currTimestamp = timestampGen();
        }
        return currTimestamp;
    }

    /**
     * 獲取當前時間戳
     */
    public long timestampGen() {
        return System.currentTimeMillis();
    }
}

參考:snowflake ID 生成算法

完整代碼:GitHub


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM