直接上代码,复制即可使用
java
public class SnowflakeIdGenerator {
private static final long START_TIMESTAMP = 1624000000000L; // 设置起始时间戳,2021-06-18 00:00:00
private static final long DATA_CENTER_ID_BITS = 5L;
private static final long WORKER_ID_BITS = 5L;
private static final long SEQUENCE_BITS = 12L;
private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;
private static long dataCenterId;
private static long workerId;
private static long sequence = 0L;
private static long lastTimestamp = -1L;
public static void init(long dataCenterId, long workerId) {
if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
throw new IllegalArgumentException(String.format("Data center ID can't be greater than %d or less than 0", MAX_DATA_CENTER_ID));
}
if (workerId > MAX_WORKER_ID || workerId < 0) {
throw new IllegalArgumentException(String.format("Worker ID can't be greater than %d or less than 0", MAX_WORKER_ID));
}
SnowflakeIdGenerator.dataCenterId = dataCenterId;
SnowflakeIdGenerator.workerId = workerId;
}
public static synchronized String generateId() {
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) & MAX_SEQUENCE;
if (sequence == 0) {
timestamp = waitNextMillis(timestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return String.valueOf(((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT)
| (dataCenterId << DATA_CENTER_ID_SHIFT)
| (workerId << WORKER_ID_SHIFT)
| sequence);
}
private static long waitNextMillis(long timestamp) {
long currentTimestamp = System.currentTimeMillis();
while (currentTimestamp <= timestamp) {
currentTimestamp = System.currentTimeMillis();
}
return currentTimestamp;
}
public static void main(String[] args) {
SnowflakeIdGenerator.init(1, 1);
for (int i = 0; i < 10; i++) {
System.out.println("Snowflake ID: " + SnowflakeIdGenerator.generateId());
}
}
}
在这个示例中,你可以通过 SnowflakeIdGenerator.init(dataCenterId, workerId);
初始化数据中心 ID 和工作 ID,然后通过 SnowflakeIdGenerator.generateId();
静态方法生成 Snowflake ID 的字符串形式。