java 实现雪花算法
时间: 2023-10-31 20:59:52 浏览: 112
Java实现雪花算法(snowflake)
雪花算法(Snowflake)是一种分布式唯一ID生成算法,主要用于解决分布式系统中生成全局唯一ID的需求。下面是一个简单的Java实现雪花算法的示例:
```java
public class SnowflakeIdGenerator {
// 定义起始的时间戳,这里使用的是2022-01-01 00:00:00
private static final long START_TIMESTAMP = 1640995200000L;
// 定义各个部分占用的位数
private static final long SEQUENCE_BIT = 12; // 序列号占用的位数
private static final long MACHINE_BIT = 5; // 机器标识占用的位数
private static final long DATACENTER_BIT = 5;// 数据中心占用的位数
// 各个部分最大值
private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
private static final long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
private static final long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
// 工作节点、数据中心和序列号
private long machineId;
private long datacenterId;
private long sequence = 0;
private long lastTimestamp = -1;
public SnowflakeIdGenerator(long machineId, long datacenterId) {
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("Invalid machine ID");
}
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("Invalid datacenter ID");
}
this.machineId = machineId;
this.datacenterId = datacenterId;
}
public synchronized long nextId() {
long currentTimestamp = System.currentTimeMillis();
if (currentTimestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id.");
}
if (currentTimestamp == lastTimestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0) {
// 当前毫秒的序列号已经用光,等待下一毫秒重新生成
currentTimestamp = getNextMillis();
}
} else {
sequence = 0;
}
lastTimestamp = currentTimestamp;
return ((currentTimestamp - START_TIMESTAMP) << (MACHINE_BIT + SEQUENCE_BIT))
| (datacenterId << SEQUENCE_BIT)
| (machineId << SEQUENCE_BIT)
| sequence;
}
protected long getNextMillis() {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
SnowflakeIdGenerator generator = new SnowflakeIdGenerator(1, 1);
long id = generator.nextId();
System.out.println("Generated ID: " + id);
}
}
```
以上代码是一个简单的雪花算法实现,可根据需要进行调整和扩展。注意,这里的实现是单机版的,如果要在分布式环境中使用,需要保证每个节点的 `machineId` 和 `datacenterId` 是唯一的。
阅读全文