用java写一个雪花算法
时间: 2024-03-13 08:23:16 浏览: 134
好的,雪花算法是一种常见的分布式 ID 生成算法,可以用于生成唯一的 ID。以下是一个使用 Java 实现的雪花算法:
```java
public class SnowflakeIdGenerator {
// 开始时间戳,用于减少 ID 的长度
private final long twepoch = 1288834974657L;
// 各部分占用的位数
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long sequenceBits = 12L;
// 最大值
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
// 工作节点 ID 和数据中心 ID
private long workerId;
private long datacenterId;
// 序列号
private long sequence = 0L;
// 上次生成 ID 的时间戳
private long lastTimestamp = -1L;
// 构造函数
public SnowflakeIdGenerator(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("workerId can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenterId can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// 生成 ID
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (timestamp == lastTimestamp) { // 同一毫秒内序列号自增
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) { // 超过序列号最大值,等待下一毫秒
timestamp = tilNextMillis(lastTimestamp);
}
} else { // 不同毫秒内序列号重置为 0
sequence = 0L;
}
lastTimestamp = timestamp;
// 时间戳(41位) | 数据中心 ID(5位) | 工作节点 ID(5位) | 序列号(12位)
return ((timestamp - twepoch) << 22) | (datacenterId << 17) | (workerId << 12) | sequence;
}
// 等待下一毫秒
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
// 获取当前时间戳
private long timeGen() {
return System.currentTimeMillis();
}
}
```
希望能够帮到你。
阅读全文