雪花算法(SnowFlake)Java實現


分布式id生成算法的有很多種,Twitter的SnowFlake就是其中經典的一種。

算法原理

SnowFlake算法生成id的結果是一個64bit大小的整數,它的結構如下圖:

1bit,不用,因為二進制中最高位是符號位,1表示負數,0表示正數。生成的id一般都是用整數,所以最高位固定為0。

41bit-時間戳,用來記錄時間戳,毫秒級。

  • 41位可以表示2^{41}-1個數字
  • 如果只用來表示正整數(計算機中正數包含0),可以表示的數值范圍是:0 至 2^{41}-1,減1是因為可表示的數值范圍是從0開始算的,而不是1
  • 也就是說41位可以表示2^{41}-1個毫秒的值,轉化成單位年則是(2^{41}-1) / (1000 * 60 * 60 * 24 *365) = 69

10bit-工作機器id,用來記錄工作機器id

  • 可以部署在2^{10} = 1024個節點,包括5位datacenterId和5位workerId
  • 5位(bit)可以表示的最大正整數是2^{5}-1 = 31,即可以用0、1、2、3、....31這32個數字,來表示不同的datecenterId或workerId

12bit-序列號,序列號,用來記錄同毫秒內產生的不同id

  • 12位(bit)可以表示的最大正整數是2^{12}-1 = 4095,即可以用0、1、2、3、....4094這4095個數字,來表示同一機器同一時間截(毫秒)內產生的4095個ID序號

由於在Java中64bit的整數是long類型,所以在Java中SnowFlake算法生成的id就是long來存儲的

SnowFlake可以保證:

  • 所有生成的id按時間趨勢遞增
  • 整個分布式系統內不會產生重復id(因為有datacenterId和workerId來做區分)

算法實現(Java)

Twitter官方給出的算法實現 是用Scala寫的,這里不做分析,可自行查看

package com.ihrm.common.utils;

public class IdWorker {

    //下面兩個每個5位,加起來就是10位的工作機器id
    private long workerId;    //工作id
    private long datacenterId;   //數據id
    //12位的序列號
    private long sequence;

    public IdWorker(long workerId, long datacenterId, long sequence) {
        // sanity check for workerId
        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));
        }
        System.out.printf("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d",
                timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);

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

    //初始時間戳
    private long twepoch = 1288834974657L;

    //長度為5位
    private long workerIdBits = 5L;
    private long datacenterIdBits = 5L;
    //最大值
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    //序列號id長度
    private long sequenceBits = 12L;
    //序列號最大值
    private long sequenceMask = -1L ^ (-1L << sequenceBits);

    //工作id需要左移的位數,12位
    private long workerIdShift = sequenceBits;
    //數據id需要左移位數 12+5=17位
    private long datacenterIdShift = sequenceBits + workerIdBits;
    //時間戳需要左移位數 12+5+5=22位
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    //上次時間戳,初始值為負數
    private long lastTimestamp = -1L;

    public long getWorkerId() {
        return workerId;
    }

    public long getDatacenterId() {
        return datacenterId;
    }

    public long getTimestamp() {
        return System.currentTimeMillis();
    }

    //下一個ID生成算法
    public synchronized long nextId() {
        long timestamp = timeGen();

        //獲取當前時間戳如果小於上次時間戳,則表示時間戳獲取出現異常
        if (timestamp < lastTimestamp) {
            System.err.printf("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp);
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                    lastTimestamp - timestamp));
        }

        //獲取當前時間戳如果等於上次時間戳(同一毫秒內),則在序列號加一;否則序列號賦值為0,從0開始。
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        //將上次時間戳值刷新
        lastTimestamp = timestamp;

        /**
         * 返回結果:
         * (timestamp - twepoch) << timestampLeftShift) 表示將時間戳減去初始時間戳,再左移相應位數
         * (datacenterId << datacenterIdShift) 表示將數據id左移相應位數
         * (workerId << workerIdShift) 表示將工作id左移相應位數
         * | 是按位或運算符,例如:x | y,只有當x,y都為0的時候結果才為0,其它情況結果都為1。
         * 因為個部分只有相應位上的值有意義,其它位上都是0,所以將各部分的值進行 | 運算就能得到最終拼接好的id
         */
        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    //獲取時間戳,並與上次時間戳比較
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    //獲取系統時間戳
    private long timeGen() {
        return System.currentTimeMillis();
    }

    //---------------測試---------------
    public static void main(String[] args) {
        IdWorker worker = new IdWorker(1, 1, 1);
        for (int i = 0; i < 30; i++) {
            System.out.println(worker.nextId());
        }
    }

}

關於本文介紹雪花算法,大家可以參考(煲煲菜的博客):https://segmentfault.com/a/1190000011282426


免責聲明!

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



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