java 版的雪花算法
时间: 2023-05-22 10:06:29 浏览: 91
您好,以下是 Java 版的雪花算法实现:
```
public class Snowflake {
// 机器ID占用的位数
private static final long MACHINE_BIT = 5L;
// 数据中心ID占用的位数
private static final long DATA_CENTER_BIT = 5L;
// 序列号占用的位数
private static final long SEQUENCE_BIT = 12L;
// 最大的机器ID和数据中心ID
private static final long MAX_MACHINE_ID = ~(-1L << MACHINE_BIT);
private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_BIT);
private static final long EPOCH = 1483200000000L;
private long machineId;
private long dataCenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public Snowflake(long machineId, long dataCenterId) {
if (machineId > MAX_MACHINE_ID || machineId < 0) {
throw new IllegalArgumentException("Machine ID can't be greater than "
+ MAX_MACHINE_ID + " or less than 0!");
}
if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
throw new IllegalArgumentException("Datacenter ID can't be greater than "
+ MAX_DATA_CENTER_ID + " or less than 0!");
}
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) & ~(-1L << SEQUENCE_BIT);
if (sequence == 0L) {
currentTimestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = currentTimestamp;
return (currentTimestamp - EPOCH) << (MACHINE_BIT + DATA_CENTER_BIT + SEQUENCE_BIT)
| dataCenterId << (MACHINE_BIT + SEQUENCE_BIT)
| machineId << SEQUENCE_BIT
| sequence;
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
希望能对您有所帮助。
阅读全文