java实现雪花算法
时间: 2023-10-21 12:22:20 浏览: 128
Java实现雪花算法(snowflake)
雪花算法(Snowflake)是一种用于生成全局唯一ID的算法,常用于分布式系统中,主要包括时间戳、机器ID和序列号三个部分。下面是一个简单的Java实现雪花算法的示例代码:
```java
public class Snowflake {
private static final long START_TIMESTAMP = 1609459200000L; // 2021-01-01 00:00:00
private long workerId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public Snowflake(long workerId) {
this.workerId = workerId;
}
public synchronized long nextId() {
long currentTimestamp = System.currentTimeMillis();
if (currentTimestamp < lastTimestamp) {
throw new IllegalStateException("Invalid system clock");
}
if (currentTimestamp == lastTimestamp) {
sequence = (sequence + 1) & 0x1FFF; // 0x1FFF = 8191
if (sequence == 0) {
currentTimestamp = waitNextMillis(currentTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = currentTimestamp;
return ((currentTimestamp - START_TIMESTAMP) << 22) |
(workerId << 12) |
sequence;
}
private long waitNextMillis(long currentTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= currentTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
使用示例:
```java
public class SnowflakeExample {
public static void main(String[] args) {
Snowflake snowflake = new Snowflake(1);
for (int i = 0; i < 10; i++) {
long id = snowflake.nextId();
System.out.println(id);
}
}
}
```
在上述示例中,通过传入不同的workerId来区分不同的机器或节点,生成全局唯一的ID。请注意,这只是一个简单的实现示例,实际应用中需要根据具体情况进行调整和优化。
阅读全文