一、算法原理

雪花算法是Twitter开源的一种分布式ID生成算法,它能生成全局唯一且有序的64位ID,非常适合在分布式系统中使用。

1. 算法结构

雪花算法生成的ID是一个64位的长整型数字,由以下几部分组成:

 

0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000

从左到右依次为:

  1. 1位符号位:始终为0,保证ID为正数

  2. 41位时间戳:记录生成ID的时间戳(毫秒级)

  3. 10位工作机器ID:

    • 5位数据中心ID(datacenterId)

    • 5位机器ID(workerId)

  4. 12位序列号:同一毫秒内生成的序列号

2. 核心原理

2.1 时间戳部分(41位)

  • 记录当前时间与自定义起始时间(epoch)的差值(毫秒数)

  • 41位可以表示的时间范围:2^41 - 1毫秒 ≈ 69年

  • 起始时间可自定义,如Twitter使用2010-11-04 09:42:54 UTC

2.2 工作机器ID(10位)

  • 最多支持2^10 = 1024个节点

  • 通常分为5位数据中心ID和5位机器ID

  • 需要人工配置或通过其他服务获取

2.3 序列号(12位)

  • 同一毫秒内生成的序列号

  • 12位支持每毫秒生成2^12 = 4096个ID

  • 当同一毫秒内生成的ID超过4096时,会等待下一毫秒

3. 算法特点

  1. 全局唯一:通过时间戳+机器ID+序列号保证

  2. 趋势递增:由于时间戳在最前面,整体ID是递增的

  3. 高性能:本地生成,不依赖数据库

  4. 时间有序:ID中包含时间戳信息

  5. 可反解:可以从ID中解析出生成时间、机器信息等

二、雪花算法工具类

  1. 代码如下:

package cn.ctg.zlt.framework.common.util.string;

import lombok.Data;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName SnowflakeIdWorker
 * @Description TODO
 * @Author jiwenjian
 * @Date 2024/8/13 下午3:55
 */
@Configuration
@Data
public class SnowflakeIdWorkerUtils {

    /** 工作机器ID(0~31) */
    private long workerId;

    /** 数据中心ID(0~31) */
    private long datacenterId;

    /** 订单支付单号 1开头 */
    private static final String PAY_CODE = "1";

    /** 订单退款单号 2开头 */
    private static final String REFUND_CODE = "2";

    /** 云卡充值单号 3开头 */
    private static final String ACCOUNT_CODE = "3";

    /** 积分批次号 4开头 */
    private static final String POINT_CODE = "4";

    // ==============================Fields===========================================
    /** 开始时间截 (2015-01-01) */
    private final long twepoch = 1420041600000L;

    /** 机器id所占的位数 */
    private final long workerIdBits = 5L;

    /** 数据标识id所占的位数 */
    private final long datacenterIdBits = 5L;

    /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /** 支持的最大数据标识id,结果是31 */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /** 序列在id中占的位数 */
    private final long sequenceBits = 12L;

    /** 机器ID向左移12位 */
    private final long workerIdShift = sequenceBits;

    /** 数据标识id向左移17位(12+5) */
    private final long datacenterIdShift = sequenceBits + workerIdBits;

    /** 时间截向左移22位(5+5+12) */
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /** 毫秒内序列(0~4095) */
    private long sequence = 0L;

    /** 上次生成ID的时间截 */
    private long lastTimestamp = -1L;

    //==============================Constructors=====================================

    /**
     * 构造函数
     */
    public SnowflakeIdWorkerUtils() {
    }

    /**
     * 支付单号
     * @return
     */
    public String getOrderNo() {
        return PAY_CODE+ nextId();
    }

    /**
     * 退款单号
     * @return
     */
    public String getRefundCode() {
        return REFUND_CODE+ nextId();
    }

    /**
     * 云卡充值单号
     * @return
     */
    public String getAccountCode() {
        return ACCOUNT_CODE+ nextId();
    }

    /**
     * 积分批次号
     * @return
     */
    public String getPointNo() {
        return POINT_CODE+ nextId();
    }

    /**
     * 构造函数
     * @param workerId 工作ID (0~31)
     * @param datacenterId 数据中心ID (0~31)
     */
    public SnowflakeIdWorkerUtils(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;
    }

    // ==============================Methods==========================================
    /**
     * 获得下一个ID (该方法是线程安全的)
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一时间生成的,则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        //时间戳改变,毫秒内序列重置
        else {
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift) //
                | (datacenterId << datacenterIdShift) //
                | (workerId << workerIdShift) //
                | sequence;
    }



    /**
     * 阻塞到下一个毫秒,直到获得新的时间戳
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    //==============================Test=============================================
    /** 测试 */
    public static void main(String[] args) {
        SnowflakeIdWorkerUtils idWorker = new SnowflakeIdWorkerUtils(1, 1);


        for (int i = 0; i < 10; i++) {
            String id = idWorker.getPointNo();
            System.out.println(id);
        }


    }
}

package cn.ctg.zlt.framework.common.util.string;

import lombok.Data;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName SnowflakeIdWorker
 * @Description TODO
 * @Author jiwenjian
 * @Date 2024/8/13 下午3:55
 */
@Configuration
@Data
public class SnowflakeIdWorkerUtils {

    /** 工作机器ID(0~31) */
    private long workerId;

    /** 数据中心ID(0~31) */
    private long datacenterId;

    /** 订单支付单号 1开头 */
    private static final String PAY_CODE = "1";

    /** 订单退款单号 2开头 */
    private static final String REFUND_CODE = "2";

    /** 云卡充值单号 3开头 */
    private static final String ACCOUNT_CODE = "3";

    /** 积分批次号 4开头 */
    private static final String POINT_CODE = "4";

    // ==============================Fields===========================================
    /** 开始时间截 (2015-01-01) */
    private final long twepoch = 1420041600000L;

    /** 机器id所占的位数 */
    private final long workerIdBits = 5L;

    /** 数据标识id所占的位数 */
    private final long datacenterIdBits = 5L;

    /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /** 支持的最大数据标识id,结果是31 */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /** 序列在id中占的位数 */
    private final long sequenceBits = 12L;

    /** 机器ID向左移12位 */
    private final long workerIdShift = sequenceBits;

    /** 数据标识id向左移17位(12+5) */
    private final long datacenterIdShift = sequenceBits + workerIdBits;

    /** 时间截向左移22位(5+5+12) */
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /** 毫秒内序列(0~4095) */
    private long sequence = 0L;

    /** 上次生成ID的时间截 */
    private long lastTimestamp = -1L;

    //==============================Constructors=====================================

    /**
     * 构造函数
     */
    public SnowflakeIdWorkerUtils() {
    }

    /**
     * 支付单号
     * @return
     */
    public String getOrderNo() {
        return PAY_CODE+ nextId();
    }

    /**
     * 退款单号
     * @return
     */
    public String getRefundCode() {
        return REFUND_CODE+ nextId();
    }

    /**
     * 云卡充值单号
     * @return
     */
    public String getAccountCode() {
        return ACCOUNT_CODE+ nextId();
    }

    /**
     * 积分批次号
     * @return
     */
    public String getPointNo() {
        return POINT_CODE+ nextId();
    }

    /**
     * 构造函数
     * @param workerId 工作ID (0~31)
     * @param datacenterId 数据中心ID (0~31)
     */
    public SnowflakeIdWorkerUtils(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;
    }

    // ==============================Methods==========================================
    /**
     * 获得下一个ID (该方法是线程安全的)
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一时间生成的,则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        //时间戳改变,毫秒内序列重置
        else {
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift) //
                | (datacenterId << datacenterIdShift) //
                | (workerId << workerIdShift) //
                | sequence;
    }



    /**
     * 阻塞到下一个毫秒,直到获得新的时间戳
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    //==============================Test=============================================
    /** 测试 */
    public static void main(String[] args) {
        SnowflakeIdWorkerUtils idWorker = new SnowflakeIdWorkerUtils(1, 1);


        for (int i = 0; i < 10; i++) {
            String id = idWorker.getPointNo();
            System.out.println(id);
        }


    }
}

使用:

// 雪花算法生成批次号
String IssueNo = new SnowflakeIdWorkerUtils(1, 1).getPointNo();

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐