分佈式id生成算法Twitter的SnowFlake

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

算法原理

SnowFlake算法生成id的結果是一個64bit大小的整數,它的結構如下圖:
在這裏插入圖片描述

  1. 1bit,不用,因爲二進制中最高位是符號位,1表示負數,0表示正數。生成的id一般都是用整數,所以最高位固定爲0。
  2. 41bit-時間戳,用來記錄時間戳,毫秒級。
    • 41位可以表示個數字,
    • 如果只用來表示正整數(計算機中正數包含0),可以表示的數值範圍是:0 至 ,減1是因爲可表示的數值範圍是從0開始算的,而不是1。
    • 也就是說41位可以表示個毫秒的值,轉化成單位年則是年
  3. 10bit-工作機器id,用來記錄工作機器id。
    • 可以部署在個節點,包括5位datacenterId和5位workerId
    • 5位(bit)可以表示的最大正整數是,即可以用0、1、2、3、…31這32個數字,來表示不同的datecenterId或workerId
  4. 12bit-序列號,序列號,用來記錄同毫秒內產生的不同id。
    • 12位(bit)可以表示的最大正整數是,即可以用0、1、2、3、…4094這4095個數字,來表示同一機器同一時間截(毫秒)內產生的4095個ID序號。

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

SnowFlake可以保證:

  1. 所有生成的id按時間趨勢遞增
  2. 整個分佈式系統內不會產生重複id(因爲有datacenterId和workerId來做區分)

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

Java版算法實現:

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());
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章