java 雪花算法生成数字id
时间: 2023-09-02 11:10:26 浏览: 100
基于雪花算法的ID生成器
5星 · 资源好评率100%
你可以使用Java编写雪花算法来生成数字ID。雪花算法是一种分布式唯一ID生成算法,它可以在多台机器上生成不重复的ID。
以下是一个简单的Java实现示例:
```java
public class SnowflakeIdGenerator {
private final long epoch = 1609459200000L; // 设置起始时间戳,例如:2021-01-01 00:00:00
private final long workerIdBits = 5L; // 机器ID所占的位数
private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 最大机器ID
private final long sequenceBits = 12L; // 序列号所占的位数
private final long workerIdShift = sequenceBits; // 机器ID向左移的位数
private final long timestampShift = sequenceBits + workerIdBits; // 时间戳向左移的位数
private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 序列号的掩码
private long workerId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public SnowflakeIdGenerator(long workerId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException("Worker ID超出范围");
}
this.workerId = workerId;
}
public synchronized long generateId() {
long timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new RuntimeException("时钟回拨异常");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - epoch) << timestampShift)
| (workerId << workerIdShift)
| sequence;
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1);
long id = idGenerator.generateId();
System.out.println(id);
}
}
```
在上面的示例中,SnowflakeIdGenerator类接受一个workerId作为参数,用于标识不同的机器。generateId()方法会生成一个唯一的数字ID。你可以根据自己的需求进行调整和扩展。
阅读全文