package cn.mbz.carsale.utils;
public class SnowflakeIdGenerator {
// 雪花算法参数
private final long twepoch = 1622505600000L; // 起始时间戳(毫秒),通常设置为系统上线时间
private final long datacenterIdBits = 5L; // 数据中心ID位数,用于标识不同的数据中心
private final long workerIdBits = 5L; // 机器ID位数,用于标识不同的机器
private final long sequenceBits = 12L; // 序列号位数,用于标识同一毫秒内生成的不同ID
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
//当前机器的workerId和数据中心datacenterId,请根据实际情况进行配置
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
/**
* 构造函数,用于初始化workerId和datacenterId。
* @param workerId 机器ID
* @param datacenterId 数据中心ID
*/
public SnowflakeIdGenerator(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
* @return 雪花算法生成的唯一ID的64位二进制字符串
*/
public synchronized String nextIdBinary() {
long timestamp = System.currentTimeMillis();
// 检查时钟回退情况
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate ID for " + (lastTimestamp - timestamp) + " milliseconds");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 序列号溢出,等待下一毫秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
// 生成最终的雪花ID
long snowflakeId = ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdShift) |
(workerId << workerIdShift) |
sequence;
// 将雪花ID转换为64位二进制字符串
String binaryId = Long.toBinaryString(snowflakeId);
// 补齐位数,不足64位的前面补0
while (binaryId.length() < 64) {
binaryId = "0" + binaryId;
}
return binaryId;
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
/**
* 生成十进制id
* @return
*/
public Long nextDecId(){
String binaryId = nextIdBinary();
return Long.parseLong(binaryId,2);
}
public static void main(String[] args) {
// 使用示例
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
for (int i = 0; i < 10; i++) {
System.out.println(idGenerator.nextDecId());
}
}
}
Java雪花算法代码
最新推荐文章于 2024-04-11 07:35:31 发布