雪花算法生成id工具类
时间: 2023-09-13 07:08:23 浏览: 196
雪花算法是一种分布式系统中生成唯一ID的算法,它可以生成一个64位的ID,其中包含了时间戳、机器ID和序列号等信息。下面是一个Java实现的雪花算法生成ID的工具类:
```java
public class SnowflakeIdGenerator {
// 起始的时间戳
private final static long START_TIMESTAMP = 1609459200000L; //2021-01-01 00:00:00
// 每一部分占用的位数
private final static long SEQUENCE_BIT = 12; // 序列号占用的位数
private final static long MACHINE_BIT = 5; // 机器标识占用的位数
private final static long DATACENTER_BIT = 5; // 数据中心占用的位数
// 每一部分的最大值
private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE_NUM = ~(-1L << SEQUENCE_BIT);
// 每一部分向左的位移
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; // 数据中心ID
private long machineId; // 机器ID
private long sequence = 0L; // 序列号
private long lastTimestamp = -1L; // 上一次生成ID的时间戳
public SnowflakeIdGenerator(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
/**
* 生成下一个唯一的ID
*
* @return Snowflake ID
*/
public synchronized long nextId() {
long timestamp = System.currentTimeMillis();
// 时钟回拨,抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
// 同一毫秒内生成ID
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE_NUM;
// 当前毫秒内的序列号已经达到最大值,等待下一毫秒再生成ID
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
}
// 不同毫秒内生成ID
else {
sequence = 0L;
}
lastTimestamp = timestamp;
// 生成ID
return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT)
| (datacenterId << DATACENTER_LEFT)
| (machineId << MACHINE_LEFT)
| sequence;
}
/**
* 等待下一个毫秒的到来
*
* @param lastTimestamp 上一次生成ID的时间戳
* @return 当前毫秒的时间戳
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
使用示例:
```java
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
long id = idGenerator.nextId();
```
其中,`datacenterId`和`machineId`分别表示数据中心ID和机器ID,可以根据实际情况设置。`nextId()`方法用于生成下一个唯一的ID。
阅读全文