java雪花算法生成主键id
时间: 2023-11-03 16:22:08 浏览: 138
Java中的雪花算法(Snowflake)可以用于生成唯一的主键ID。下面是一个简单的实现示例:
```java
public class SnowflakeIdGenerator {
private final static long START_TIMESTAMP = 1614556800000L; // 设置起始时间戳,这里假设为2021-03-01 00:00:00
private final static long DATA_CENTER_ID_BITS = 5L; // 数据中心ID所占的位数
private final static long WORKER_ID_BITS = 5L; // 工作机器ID所占的位数
private final static long SEQUENCE_BITS = 12L; // 序列号所占的位数
private final static long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS); // 支持的最大数据中心ID数量
private final static long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); // 支持的最大工作机器ID数量
private final static long WORKER_ID_SHIFT = SEQUENCE_BITS; // 工作机器ID左移位数
private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; // 数据中心ID左移位数
private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS; // 时间戳左移位数
private final static long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); // 序列号掩码
private long workerId; // 工作机器ID
private long dataCenterId; // 数据中心ID
private long sequence = 0L; // 序列号
private long lastTimestamp = -1L; // 上次生成ID的时间戳
public SnowflakeIdGenerator(long dataCenterId, long workerId) {
if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
throw new IllegalArgumentException("Data center ID can't be greater than " + MAX_DATA_CENTER_ID + " or less than 0");
}
if (workerId > MAX_WORKER_ID || workerId < 0) {
throw new IllegalArgumentException("Worker ID can't be greater than " + MAX_WORKER_ID + " or less than 0");
}
this.dataCenterId = dataCenterId;
this.workerId = workerId;
}
public synchronized long generateId() {
long currentTimestamp = System.currentTimeMillis();
if (currentTimestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate ID for " + (lastTimestamp - currentTimestamp) + " milliseconds");
}
if (currentTimestamp == lastTimestamp) {
sequence = (sequence + 1) & SEQUENCE_MASK;
if (sequence == 0) {
currentTimestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = currentTimestamp;
return ((currentTimestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT)
| (dataCenterId << DATA_CENTER_ID_SHIFT)
| (workerId << WORKER_ID_SHIFT)
| sequence;
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
// 创建一个SnowflakeIdGenerator实例,传入数据中心ID和工作机器ID
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
// 生成ID
long id = idGenerator.generateId();
System.out.println("Generated ID: " + id);
}
}
```
这样就可以使用雪花算法在Java中生成唯一的主键ID了。
阅读全文