Java實現(xiàn)雪花算法(SnowFlake)

雪花算法SnowFlake可以保證:

1.所有生成的id按時間趨勢遞增
2.整個分布式系統(tǒng)內(nèi)不會產(chǎn)生重復id(通過workerId和datacenterId來做區(qū)分)

算法實現(xiàn)

import java.util.Random;

public class IdWorker {

    //下面兩個每個5位,加起來就是10位的工作機器id
    private long workerId;    //工作ID  2進制5位  數(shù)值0-31
    private long datacenterId;   //數(shù)據(jù)id 2進制5位  數(shù)值0-31
    //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需要左移的位數(shù),12位
    private long workerIdShift = sequenceBits;
    //數(shù)據(jù)id需要左移位數(shù) 12+5=17位
    private long datacenterIdShift = sequenceBits + workerIdBits;
    //時間戳需要左移位數(shù) 12+5+5=22位
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

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

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

        //獲取當前時間戳如果小于上次時間戳,則表示時間戳獲取出現(xiàn)異常
        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));
        }

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

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

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

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

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

    /**
     * 這里簡單實現(xiàn),通過隨機數(shù)生成工作ID、數(shù)據(jù)ID
     * 不生成重復id要通過datacenterId和workerId來做區(qū)分
     */
    private static class SingletonClassInstance {
        static Random random = new Random();
        private static final IdWorker instance = new IdWorker(random.nextInt(31), random.nextInt(31), 1);
    }

    /**
     * 單例調(diào)用入口
     */
    public static IdWorker getInstance() {
        return SingletonClassInstance.instance;
    }

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

文章代碼參考自煲煲菜的博客
如有侵權(quán)之處請留言告知,會立即刪除。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容