用java写一个雪花算法
时间: 2024-03-13 12:20:55 浏览: 52
雪花算法java版实现
5星 · 资源好评率100%
以下是使用Java编写的雪花算法示例代码:
```java
public class SnowflakeAlgorithm {
private final static long START_STAMP = 1546300800000L; // 起始时间戳,2019-01-01 00:00:00
private final static long SEQUENCE_BIT = 12; // 序列号占用的位数
private final static long MACHINE_BIT = 5; // 机器标识占用的位数
private final static long DATACENTER_BIT = 5; // 数据中心占用的位数
private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE_NUM = ~(-1L << SEQUENCE_BIT);
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; // 数据中心ID
private long machineId; // 机器ID
private long sequence; // 序列号
private long lastTimestamp; // 上次生成ID的时间戳
public SnowflakeAlgorithm(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
this.sequence = 0L;
this.lastTimestamp = -1L;
}
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_NUM;
if (sequence == 0) {
currentTimestamp = nextTimestamp();
}
} else {
sequence = 0L;
}
lastTimestamp = currentTimestamp;
return ((currentTimestamp - START_STAMP) << TIMESTAMP_LEFT) |
(datacenterId << DATACENTER_LEFT) |
(machineId << MACHINE_LEFT) |
sequence;
}
private long nextTimestamp() {
long currentTimestamp = System.currentTimeMillis();
while (currentTimestamp <= lastTimestamp) {
currentTimestamp = System.currentTimeMillis();
}
return currentTimestamp;
}
}
```
使用示例:
```java
public class SnowflakeAlgorithmTest {
public static void main(String[] args) {
SnowflakeAlgorithm snowflake = new SnowflakeAlgorithm(1, 1);
for (int i = 0; i < 10; i++) {
long id = snowflake.nextId();
System.out.println(id);
}
}
}
```
阅读全文