Java 雪花算法 workerid生成算法
时间: 2024-01-29 21:03:50 浏览: 101
Java 雪花算法(Snowflake)是一种分布式全局唯一 ID 生成算法,由 Twitter 公司提出。该算法可以在分布式系统中生成唯一 ID,同时也保证了 ID 的有序性和时间戳的精度。其中 workerid 是生成算法中的一个关键因素,下面是一种 Java 实现的 workerid 生成算法:
```java
public class SnowflakeIdGenerator {
private static final long twepoch = 1288834974657L;
private static final long workerIdBits = 5L;
private static final long datacenterIdBits = 5L;
private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private static final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private static final long sequenceBits = 12L;
private static final long workerIdShift = sequenceBits;
private static final long datacenterIdShift = sequenceBits + workerIdBits;
private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private static final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public SnowflakeIdGenerator(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdShift) |
(workerId << workerIdShift) |
sequence;
}
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
protected long timeGen() {
return System.currentTimeMillis();
}
}
```
该代码中的 workerid 生成算法使用了位运算和时间戳的方式,通过将 workerid、datacenterid、时间戳和序列号进行位移和或运算,生成一个 64 位的唯一 ID。其中 workerid 和 datacenterid 需要在初始化时传入,可以通过配置文件等方式实现。
阅读全文