雪花算法(Snowflake)是一种用于生成唯一ID的分布式算法,由Twitter开源。它可以在不依赖数据库的情况下生成全局唯一的ID。雪花算法生成的ID是一个64位的长整型数字,结构如下:
+------------------+
| 41 | 机器标识(10位)|
+------------------+
| 0 | 序列号(12位)|
+------------------+
| 1 | 时间戳(41位)|
+------------------+
| 30 | 数据中心ID(5位)|
+------------------+
| 1 | 工作机器ID(5位)|
+------------------+
要使用雪花算法生成唯一ID,你需要按照以下步骤操作:
- 定义一个类,例如
SnowflakeIdWorker
,并实现以下方法:
```java public class SnowflakeIdWorker { // 机器标识(10位) private final long workerId; // 序列号(12位) private final long sequence; // 时间戳(41位) private final long lastTimestamp = -1L; // 数据中心ID(5位) private final long datacenterId; // 工作机器ID(5位) private final long workerIdBits = 5L; // 序列号位数 private final long sequenceBits = 12L; // 时间戳位数 private final long timestampLeftShift = sequenceBits; // 数据中心ID位数 private final long datacenterIdBits = workerIdBits; // 总位数 private final long maxWorkerId = -1L ^ (-1L << workerIdBits); private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private final long sequenceMask = -1L ^ (-1L << sequenceBits);
// 构造函数
public SnowflakeIdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException("worker Id can't be greater than " + maxWorkerId || "or less than 0");
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException("datacenter Id can't be greater than " + maxDatacenterId || "or less than 0");
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// 生成唯一ID的方法
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdBits) |
(workerId << workerIdBits) |
sequence;
}
// 获取当前时间戳的方法
private long timeGen() {
return System.currentTimeMillis();
}
// 等待下一毫秒的方法
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
} ```
- 在需要生成唯一ID的地方,创建
SnowflakeIdWorker
实例并调用nextId()
方法:
java
public class Main {
public static void main(String[] args) {
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 1);
long uniqueId = idWorker.nextId();
System.out.println("Generated unique ID: " + uniqueId);
}
}
这样就可以使用雪花算法生成全局唯一的ID了。注意,雪花算法适用于分布式系统,但在单点场景下可能会出现问题。在实际应用中,请根据需求选择合适的ID生成策略。