java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java雪花id生成算法

Java使用雪花id生成算法详解

作者:码畜c

SnowFlake算法,是Twitter开源的分布式id生成算法,在2014年开源,开源的版本由scala编写。其核心思想就是-使用一个64bit的long型的数字作为全局唯一id

什么是雪花算法

雪花算法的本质为生成一个64位长度的具有自增性的分布式全局唯一id。在64bits中,会对不同段的位进行划分。可分为:

位段详解

优点

问题

依赖服务器时间。若服务器时钟回拨,可能会导致生成的id重复。可在代码中新增lastTimeMillis字段,在获取nextId时根据系统当前时间进行判断解决。

但若不进行持久化处理,服务重启后发生时钟回拨依旧会出现重复问题。

实际应用

具体实现

/**
 * Created by QQ.Cong on 2022-07-22 / 9:48
 *
 * @author: CongQingquan
 * @Description: Snowflake util
 */
public class SnowflakeUtils {
    // ============================== Basic field ==============================//
    // Datacenter id
    private long datacenterId;
    // Worker id
    private long workerId;
    // Increment sequence
    private long sequence;
    // ============================== Bits ==============================//
    // Bits of datacenter id
    private long datacenterIdBits;
    // Bits of worker id
    private long workerIdBits;
    // Bits of sequence
    private long sequenceBits;
    // ============================== Largest ==============================//
    // Largest datacenter id
    private long largestDatacenterId;
    // Largest worker id
    private long largestWorkerId;
    // Largest sequence
    private long largestSequence;
    // ============================== Shift ==============================//
    // Left shift num of worker id
    private long workerIdShift;
    // Left shift num of datacenter id
    private long datacenterIdShift;
    // Left shift num of timestamp
    private long timestampShift;
    // ============================== Other ==============================//
    // Epoch
    private long epoch;
    // The timestamp that last get snowflake id
    private long lastTimestamp;
    // ============================== End ==============================//
    public SnowflakeUtils(long dataCenterId, long workerId) {
        // Default epoch: 2022-07-22 00:00:00
        this(1658419200000L, -1L, dataCenterId, workerId, 5L, 5L, 5L);
    }
    public SnowflakeUtils(long epoch, long lastTimestamp, long datacenterId, long workerId,
        long datacenterIdBits, long workerIdBits, long sequenceBits) {
        this.epoch = epoch;
        this.lastTimestamp = lastTimestamp;
        this.datacenterId = datacenterId;
        this.workerId = workerId;
        this.sequence = 0L;
        this.datacenterIdBits = datacenterIdBits;
        this.workerIdBits = workerIdBits;
        this.sequenceBits = sequenceBits;
        this.largestDatacenterId = ~(-1L << datacenterIdBits);
        this.largestWorkerId = ~(-1L << workerIdBits);
        this.largestSequence = ~(-1L << sequenceBits);
        if (datacenterId > largestDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(
                String.format("The datacenter id param can't be greater than %s or less than 0",
                    largestDatacenterId));
        }
        if (workerId > largestWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                String.format("The worker id param can't be greater than %s or less than 0",
                    largestWorkerId));
        }
        this.workerIdShift = sequenceBits;
        this.datacenterIdShift = workerIdShift + workerIdBits;
        this.timestampShift = datacenterIdShift + datacenterIdBits;
    }
    /**
     * Get snowflake id
     * @return
     */
    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        // 若时钟回退
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                "System clock moved backward, cannot to generate snowflake id");
        }
        // 若当前毫秒内多次生成雪花id
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & largestSequence;
            // 序列溢出
            if (sequence == 0) {
                timestamp = waitUntilNextMilli(timestamp);
            }
        }
        // 若当前毫秒内首次生成雪花id
        else {
            sequence = 0L;
        }
        // 更新获取雪花id的时间戳
        lastTimestamp = timestamp;
        // 生成雪花id (通过位或运算符进行拼接)
        return ((timestamp - epoch) << timestampShift) // 时间戳段
            | (datacenterId << datacenterIdShift) // 机器码段
            | (workerId << workerIdShift) // 机器码段
            | sequence; // 自增序列段
    }
    /**
     * Wait until next millisecond
     * @param lastTimestamp
     * @return
     */
    private long waitUntilNextMilli(long lastTimestamp) {
        long currentTimeMillis;
        do {
            currentTimeMillis = System.currentTimeMillis();
        }
        while (currentTimeMillis <= lastTimestamp);
        return currentTimeMillis;
    }
    /**
     * Get util instance
     * @param dataCenterId
     * @param workerId
     * @return
     */
    public static SnowflakeUtils getInstance(long dataCenterId, long workerId) {
        return new SnowflakeUtils(dataCenterId, workerId);
    }
}

到此这篇关于Java使用雪花id生成算法详解的文章就介绍到这了,更多相关Java雪花id生成算法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文