package com.yonyou.ucf.mdf.util;
public class SnowflakeIdGenerator {
private static final long START_TIMESTAMP = 1620000000000L; // 设置起始时间戳,单位为毫秒
private static final long MAX_WORKER_ID = 1023L; // 最大机器ID
private static final long WORKER_ID_BITS = 10L; // 机器ID所占位数
private static final long SEQUENCE_BITS = 9L; // 序列号所占位数
private long workerId; // 机器ID
private long sequence = 0L; // 序列号
private long lastTimestamp = -1L; // 上次生成ID的时间戳
public SnowflakeIdGenerator(long workerId) {
if (workerId > MAX_WORKER_ID || workerId < 0) {
throw new IllegalArgumentException("Worker ID 超出范围");
}
this.workerId = workerId;
}
public synchronized String nextId() {
long currentTimestamp = System.currentTimeMillis();
if (currentTimestamp < lastTimestamp) {
throw new RuntimeException("时间回退,无法生成ID");
}
if (currentTimestamp == lastTimestamp) {
sequence = (sequence + 1) & ((1 << SEQUENCE_BITS) - 1);
if (sequence == 0) {
currentTimestamp = waitNextMillis(currentTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = currentTimestamp;
long id = ((currentTimestamp - START_TIMESTAMP) << (WORKER_ID_BITS + SEQUENCE_BITS))
| (workerId << SEQUENCE_BITS)
| sequence;
return String.valueOf(id);
}
private long waitNextMillis(long currentTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= currentTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
使用
// 雪花算法生成19位id
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1);
String id = idGenerator.nextId();
System.out.println("生成的ID: " + id);