雪花算法工具类 java
时间: 2023-09-13 13:08:20 浏览: 211
以下是一个简单的雪花算法工具类的 Java 实现:
```java
public class SnowflakeIdGenerator {
private final long epoch = 1420041600000L; // 起始时间戳,用于缩小时间戳范围,可根据实际情况调整
private final long workerIdBits = 5L; // 机器 ID 所占位数
private final long dataCenterIdBits = 5L; // 数据中心 ID 所占位数
private final long sequenceBits = 12L; // 序列号所占位数
private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 机器 ID 最大值
private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits); // 数据中心 ID 最大值
private final long maxSequence = -1L ^ (-1L << sequenceBits); // 序列号最大值
private final long workerIdShift = sequenceBits; // 机器 ID 向左移动位数
private final long dataCenterIdShift = sequenceBits + workerIdBits; // 数据中心 ID 向左移动位数
private final long timestampShift = sequenceBits + workerIdBits + dataCenterIdBits; // 时间戳向左移动位数
private long workerId; // 机器 ID
private long dataCenterId; // 数据中心 ID
private long sequence = 0L; // 序列号
private long lastTimestamp = -1L; // 上次生成的时间戳
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("Data center ID can't be greater than " + maxDataCenterId + " or less than 0");
}
this.workerId = workerId;
this.dataCenterId = dataCenterId;
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards, refusing to generate ID");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & maxSequence;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - epoch) << timestampShift) |
(dataCenterId << dataCenterIdShift) |
(workerId << workerIdShift) |
sequence;
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
}
```
使用方法:
```java
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1); // 创建一个 ID 生成器,传入机器 ID 和数据中心 ID
long id = idGenerator.nextId(); // 生成 ID
```
注意事项:
- 如果在同一毫秒内生成的 ID 数量超过了序列号所占的位数,将会进入下一毫秒生成 ID。
- 如果系统时间被回拨,将会抛出异常,应该记录异常并等待时间同步后再生成 ID。
阅读全文