雪花算法(snowflake)的JAVA實現

snowflake算法由twitter公司出品,原始版本是scala版,用於生成分佈式ID,結構圖:git

算法描述:github

  • 最高位是符號位,始終爲0,不可用。
  • 41位的時間序列,精確到毫秒級,41位的長度能夠使用69年。時間位還有一個很重要的做用是能夠根據時間進行排序。
  • 10位的機器標識,10位的長度最多支持部署1024個節點
  • 12位的計數序列號,序列號即一系列的自增id,能夠支持同一節點同一毫秒生成多個ID序號,12位的計數序列號支持每一個節點每毫秒產生4096個ID序號

Java實現:算法

package com.zhi.idworker;

/**
 * 分佈式雪花ID算法
 * 
 * @author zhi
 * @since 2019年5月14日16:51:06
 *
 */
public class SnowFlake {
    /**
     * 起始的時間戳
     */
    private final static long twepoch = 1557825652094L;

    /**
     * 每一部分佔用的位數
     */
    private final static long workerIdBits = 5L;
    private final static long datacenterIdBits = 5L;
    private final static long sequenceBits = 12L;

    /**
     * 每一部分的最大值
     */
    private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    private final static long maxSequence = -1L ^ (-1L << sequenceBits);

    /**
     * 每一部分向左的位移
     */
    private final static long workerIdShift = sequenceBits;
    private final static long datacenterIdShift = sequenceBits + workerIdBits;
    private final static long timestampShift = sequenceBits + workerIdBits + datacenterIdBits;

    private long datacenterId; // 數據中心ID
    private long workerId; // 機器ID
    private long sequence = 0L; // 序列號
    private long lastTimestamp = -1L; // 上一次時間戳

    public SnowFlake(long workerId, long datacenterId) {
        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;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format(
                    "Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & maxSequence;
            if (sequence == 0L) {
                timestamp = tilNextMillis();
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;

        return (timestamp - twepoch) << timestampShift // 時間戳部分
                | datacenterId << datacenterIdShift // 數據中心部分
                | workerId << workerIdShift // 機器標識部分
                | sequence; // 序列號部分
    }

    private long tilNextMillis() {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }
}
相關文章
相關標籤/搜索