雪花算法工具类SnowFlakeUtils生成全局唯一ID

@Slf4j
public class SnowFlakeUtils {

    private static SnowFlakeUtils flowIdWorker = new SnowFlakeUtils(1);
    private final long id;
    /**
     * 时间起始标记点,作为基准,一般取系统的最近时间
     */
    private final long epoch = 1605014822000L;
    /**
     * 机器标识位数
     */
    private final long workerIdBits = 10L;
    /**
     * 机器ID最大值: 1023
     */
    private final long maxWorkerId = -1L ^ -1L << this.workerIdBits;
    /**
     * 毫秒内自增位
     */
    private final long sequenceBits = 12L;

    /**
     * 12
     */
    private final long workerIdShift = this.sequenceBits;
    /**
     * 22
     */
    private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;
    /**
     * 4095,111111111111,12位
     */
    private final long sequenceMask = -1L ^ -1L << this.sequenceBits;
    /**
     * 0,并发控制
     */
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    private SnowFlakeUtils(long id) {
        if (id > this.maxWorkerId || id < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId));
        }
        this.id = id;
    }

    public static SnowFlakeUtils getFlowIdInstance() {
        return flowIdWorker;
    }

    /**
     * 获得系统当前毫秒数
     */
    private static long timeGen() {
        return System.currentTimeMillis();
    }

    public synchronized long nextId() {
        long timestamp = timeGen();
        if (this.lastTimestamp == timestamp) {
            //如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始
            this.sequence = this.sequence + 1 & this.sequenceMask;
            if (this.sequence == 0) {
                // 重新生成timestamp
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {
            this.sequence = 0;
        }

        if (timestamp < this.lastTimestamp) {
            log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
            return -1;
        }

        this.lastTimestamp = timestamp;
        return timestamp - this.epoch << this.timestampLeftShift | this.id << this.workerIdShift | this.sequence;
    }

    /**
     * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            SnowFlakeUtils snowFlakeUtil = SnowFlakeUtils.getFlowIdInstance();
            System.out.println(snowFlakeUtil.nextId());
        }
    }
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
雪花算法是一种分布式系统中生成唯一ID的算法,它可以生成一个64位的ID,其中包含了时间戳、机器ID和序列号等信息。下面是一个Java实现的雪花算法生成ID工具类: ```java public class SnowflakeIdGenerator { // 起始的时间戳 private final static long START_TIMESTAMP = 1609459200000L; //2021-01-01 00:00:00 // 每一部分占用的位数 private final static long SEQUENCE_BIT = 12; // 序列号占用的位数 private final static long MACHINE_BIT = 5; // 机器标识占用的位数 private final static long DATACENTER_BIT = 5; // 数据中心占用的位数 // 每一部分的最大值 private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT); private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT); private final static long MAX_SEQUENCE_NUM = ~(-1L << SEQUENCE_BIT); // 每一部分向左的位移 private final static long MACHINE_LEFT = SEQUENCE_BIT; private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT; private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT; private long datacenterId; // 数据中心ID private long machineId; // 机器ID private long sequence = 0L; // 序列号 private long lastTimestamp = -1L; // 上一次生成ID的时间戳 public SnowflakeIdGenerator(long datacenterId, long machineId) { if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) { throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0"); } if (machineId > MAX_MACHINE_NUM || machineId < 0) { throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0"); } this.datacenterId = datacenterId; this.machineId = machineId; } /** * 生成下一个唯一ID * * @return Snowflake ID */ public synchronized long nextId() { long timestamp = System.currentTimeMillis(); // 时钟回拨,抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException("Clock moved backwards. Refusing to generate id"); } // 同一毫秒内生成ID if (lastTimestamp == timestamp) { sequence = (sequence + 1) & MAX_SEQUENCE_NUM; // 当前毫秒内的序列号已经达到最大值,等待下一毫秒再生成ID if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } // 不同毫秒内生成ID else { sequence = 0L; } lastTimestamp = timestamp; // 生成ID return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT) | (datacenterId << DATACENTER_LEFT) | (machineId << MACHINE_LEFT) | sequence; } /** * 等待下一个毫秒的到来 * * @param lastTimestamp 上一次生成ID的时间戳 * @return 当前毫秒的时间戳 */ private long tilNextMillis(long lastTimestamp) { long timestamp = System.currentTimeMillis(); while (timestamp <= lastTimestamp) { timestamp = System.currentTimeMillis(); } return timestamp; } } ``` 使用示例: ```java SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1); long id = idGenerator.nextId(); ``` 其中,`datacenterId`和`machineId`分别表示数据中心ID和机器ID,可以根据实际情况设置。`nextId()`方法用于生成下一个唯一ID

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值