天天看點

魔改後的雪花算法,生成13位long類型ID,适用于單機版,避免平行越權魔改後的雪花算法

魔改後的雪花算法

生成13位long類型ID,适用于單機版,避免平行越權

  • List item
public class IdWorker{
    //12位的序列号
    private static long sequence;

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

    //序列号id長度
    private static long sequenceBits = 4L;
    //序列号最大值
    private static long sequenceMask = -1L ^ (-1L << sequenceBits);

    //時間戳需要左移位數 4位
    private static long timestampLeftShift = sequenceBits;

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


    //下一個ID生成算法
    public static 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
         */
        System.out.println("(timestamp - twepoch) :" + (timestamp - twepoch));
        System.out.println("front :" + ((timestamp - twepoch) << timestampLeftShift));
        System.out.println("sequence :" + sequence);
        return ((timestamp - twepoch) << timestampLeftShift) | sequence;
    }

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

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

}