java中使用雪花算法(Snowflake)为分布式系统生成全局唯一ID
在Java中使用雪花算法生成全局唯一ID的示例代码如下:
import java.util.concurrent.atomic.AtomicLong;
public class SnowflakeIdGenerator {
// 64位ID的各个部分所占的位数
private final long twepoch = 1288834974657L; // 起始时间戳 (2010-11-04 09:42:54.657)
private final long workerIdBits = 5L; // 工作机器ID所占的位数
private final long datacenterIdBits = 5L; // 数据中心ID所占的位数
private final long sequenceBits = 12L; // 序列号所占的位数
// 这些位都是直接按位或(|)运算,所以这里需要左移运算符(<<)
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampShift = sequenceBits + workerIdBits + datacenterIdBits;
private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 生成序列的掩码
private long workerId; // 工作机器ID
private long datacenterId; // 数据中心ID
private long sequence = 0L; // 序列号
private long lastTimestamp = -1L; // 上一次生成ID的时间戳
private AtomicLong id = new AtomicLong(0);
// 构造函数,传入工作机器ID和数据中心ID
public SnowflakeIdGenerator(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException("workerId can't be greater than %d or less than 0");
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than %d or less than 0");
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// 生成下一个ID
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 = 0;
}
lastTimestamp = timestamp;
id.set((timestamp - twepoch) << timestampShift | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence);
return id.get();
}
// 获取当前时间戳
protected long timeGen() {
return System.currentTimeMillis();
}
// 等待下一个毫秒的到来,用于解决时钟回拨问题
protected long tilNextMil
评论已关闭