使用java写一个雪花算法
时间: 2023-06-06 12:08:06 浏览: 124
好的,我可以为您提供关于雪花算法的代码示例。以下是使用Java实现的雪花算法:
```java
public class Snowflake {
private static final long START_STMP = 1480166465631L; // 起始的时间戳
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_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private static final long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
private static final long MACHINE_LEFT = SEQUENCE_BIT;
private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private static final long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; // 数据中心
private long machineId; // 机器标识
private long sequence = 0L; // 序列号
private long lastStmp = -1L; // 上一次时间戳
public Snowflake(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("Invalid datacenterId");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("Invalid machineId");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTAMP_LEFT |
datacenterId << DATACENTER_LEFT |
machineId << MACHINE_LEFT |
sequence;
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
}
```
您可以使用上面的代码示例来生成雪花算法的ID。
阅读全文