Java雪花算法代码

package cn.mbz.carsale.utils;
public class SnowflakeIdGenerator {
    // 雪花算法参数
    private final long twepoch = 1622505600000L;  // 起始时间戳(毫秒),通常设置为系统上线时间
    private final long datacenterIdBits = 5L;     // 数据中心ID位数,用于标识不同的数据中心
    private final long workerIdBits = 5L;         // 机器ID位数,用于标识不同的机器
    private final long sequenceBits = 12L;        // 序列号位数,用于标识同一毫秒内生成的不同ID
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    private final long workerIdShift = sequenceBits;
    private final long datacenterIdShift = sequenceBits + workerIdBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);
    //当前机器的workerId和数据中心datacenterId,请根据实际情况进行配置
    private long workerId;
    private long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;
    /**
     * 构造函数,用于初始化workerId和datacenterId。
     * @param workerId     机器ID
     * @param datacenterId 数据中心ID
     */
    public SnowflakeIdGenerator(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException("Worker ID can't be greater than " + maxWorkerId + " or less than 0");
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID can't be greater than " + maxDatacenterId + " or less than 0");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }
    /**
     * 生成下一个唯一 二进制 ID
     * @return 雪花算法生成的唯一ID的64位二进制字符串
     */
    public synchronized String nextIdBinary() {
        long timestamp = System.currentTimeMillis();
        // 检查时钟回退情况
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID for " + (lastTimestamp - timestamp) + " milliseconds");
        }
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                // 序列号溢出,等待下一毫秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        // 生成最终的雪花ID
        long snowflakeId = ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
        // 将雪花ID转换为64位二进制字符串
        String binaryId = Long.toBinaryString(snowflakeId);
        // 补齐位数,不足64位的前面补0
        while (binaryId.length() < 64) {
            binaryId = "0" + binaryId;
        }
        return binaryId;
    }
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
    /**
     * 生成十进制id
     * @return
     */
    public  Long  nextDecId(){
        String binaryId = nextIdBinary();
        return  Long.parseLong(binaryId,2);
    }
    public static void main(String[] args) {
        // 使用示例
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        for (int i = 0; i < 10; i++) {
            System.out.println(idGenerator.nextDecId());
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值