雪花算法單例雙重檢查工具類 + yml自定義配置序列機器號實現自動生成ID

 

創建工具類

SnowFlakeGenerateIDUtils
@Component
//@ConfigurationProperties(prefix = "snow-flake")
//@PropertySource(value = {"classpath:/application.yml"}, encoding = "utf-8")
public class SnowFlakeGenerateIDUtils {
    //因爲二進制裏第一個 bit 如果是 1,那麼都是負數,但是我們生成的 id 都是正數,所以第一個 bit 統一都是 0。

    //機器ID  2進制5位  32位減掉1位 31個
    private long workerId;
    //機房ID 2進制5位  32位減掉1位 31個
    private long datacenterId;
    //代表一毫秒內生成的多個id的最新序號  12位 4096 -1 = 4095 個
    private long sequence;
    //設置一個時間初始值    2^41 - 1   差不多可以用69年
    private long twepoch = 1585644268888L;
    //5位的機器id
    private long workerIdBits = 5L;
    //5位的機房id
    private long datacenterIdBits = 5L;
    //每毫秒內產生的id數 2 的 12次方
    private long sequenceBits = 12L;
    // 這個是二進制運算,就是5 bit最多隻能有31個數字,也就是說機器id最多隻能是32以內
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);
    // 這個是一個意思,就是5 bit最多隻能有31個數字,機房id最多隻能是32以內
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    private long workerIdShift = sequenceBits;
    private long datacenterIdShift = sequenceBits + workerIdBits;
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private long sequenceMask = -1L ^ (-1L << sequenceBits);
    //記錄產生時間毫秒數,判斷是否是同1毫秒
    private long lastTimestamp = -1L;
    private int count = 1;

    public long getWorkerId() {
        return workerId;
    }

    public long getDatacenterId() {
        return datacenterId;
    }

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

    //public static SnowFlakeGenerateIDUtils snowWork = new SnowFlakeGenerateIDUtils(1,1,1);
    //用yml注入@value 靜態變量賦值行不通
    public static long currentWorkerId;//當前機器
    public static long currentDatacenterId;//當前機房
    public static long currentSequence;//當前序列號
    public volatile static SnowFlakeGenerateIDUtils snowWork = null;

    public static String getSnowId() {
        //單例,解決併發問題
        if (snowWork == null) {
            synchronized (SnowFlakeGenerateIDUtils.class) {
                if (snowWork == null) {
                    snowWork = new SnowFlakeGenerateIDUtils(currentWorkerId, currentDatacenterId, currentSequence);
                }
            }
        }
        Long nextId = snowWork.nextId();
        return nextId.toString();
    }

    public SnowFlakeGenerateIDUtils() {
    }

    /***
     * 功能描述: 
     * 〈〉
     * @Param: [workerId:機器ID, datacenterId:機房ID, sequence:序列號]
     * @Return:
     * @Author: by
     * @Date: 2020/5/6 11:45
     */
    public SnowFlakeGenerateIDUtils(long workerId, long datacenterId, long sequence) {
        // 檢查機房id和機器id是否超過31 不能小於0
        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));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.sequence = sequence;
    }

    // 這個是核心方法,通過調用nextId()方法,讓當前這臺機器上的snowflake算法程序生成一個全局唯一的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));
        }

        // 下面是說假設在同一個毫秒內,又發送了一個請求生成一個id
        // 這個時候就得把seqence序號給遞增1,最多就是4096
        if (lastTimestamp == timestamp) {

            // 這個意思是說一個毫秒內最多隻能有4096個數字,無論你傳遞多少進來,
            //這個位運算保證始終就是在4096這個範圍內,避免你自己傳遞個sequence超過了4096這個範圍
            //4095:111111111111  ==  sequenceMask
            //4096:1000000000000
            //當sequence大於4095,與運算 1000000000000 & 111111111111 =0 0000 0000 0000 0000
            //即sequence =0
            sequence = (sequence + 1) & sequenceMask;
            //System.out.println("同一毫秒:\t" + timestamp + ",生成ID數:\t" + count);
            count++;
            //當某一毫秒的時間,產生的id數 超過4095,系統會進入等待,直到下一毫秒,系統繼續產生ID
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
                count = 1;
            }

        } else {
            sequence = 0;
            count = 1;
        }
        // 這兒記錄一下最近一次生成id的時間戳,單位是毫秒
        lastTimestamp = timestamp;
        // 這兒就是最核心的二進制位運算操作,生成一個64bit的id
        // 先將當前時間戳左移,放到41 bit那兒;將機房id左移放到5 bit那兒;將機器id左移放到5 bit那兒;將序號放最後12 bit
        // 最後拼接起來成一個64 bit的二進制數字,轉換成10進制就是個long型
        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) | sequence;
    }

    /**
     * 當某一毫秒的時間,產生的id數 超過4095,系統會進入等待,直到下一毫秒,系統繼續產生ID
     *
     * @param lastTimestamp
     * @return
     */
    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) {
        SnowFlakeGenerateIDUtils worker = new SnowFlakeGenerateIDUtils(1, 1, 1);
        for (int i = 0; i < 10; i++) {
            System.out.println(worker.nextId());
        }
    }

    @Value("${snow-id.currentWorkerId}")
    public void setCurrentWorkerId(long currentWorkerId) {
        SnowFlakeGenerateIDUtils.currentWorkerId = currentWorkerId;
    }
    @Value("${snow-id.currentDatacenterId}")
    public void setCurrentDatacenterId(long currentDatacenterId) {
        SnowFlakeGenerateIDUtils.currentDatacenterId = currentDatacenterId;
    }
    @Value("${snow-id.currentSequence}")
    public void setCurrentSequence(long currentSequence) {
        SnowFlakeGenerateIDUtils.currentSequence = currentSequence;
    }
}

 

yml參數配置

snow-id:
  currentWorkerId: 1
  currentDatacenterId: 1
  currentSequence: 1

 

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