java分布式生成序号工具
时间: 2023-08-11 08:40:27 浏览: 117
在分布式系统中,生成唯一的序号是一个常见的需求。为了解决这个问题,可以使用Snowflake算法,它是Twitter开源的一个分布式ID生成算法,可以生成唯一的64位整数。
以下是一个Java实现的分布式生成序号工具,基于Snowflake算法:
```
public class SnowflakeIdGenerator {
private static final long START_TIME = 1483200000000L; // 2017-01-01 00:00:00
private static final long WORKER_ID_BITS = 5L;
private static final long DATA_CENTER_ID_BITS = 5L;
private static final long SEQUENCE_BITS = 12L;
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;
private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
private long workerId;
private long dataCenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public SnowflakeIdGenerator(long workerId, long dataCenterId) {
if (workerId >= (1L << WORKER_ID_BITS) || workerId < 0) {
throw new IllegalArgumentException("workerId must be between 0 and " + ((1L << WORKER_ID_BITS) - 1));
}
if (dataCenterId >= (1L << DATA_CENTER_ID_BITS) || dataCenterId < 0) {
throw new IllegalArgumentException("dataCenterId must be between 0 and " + ((1L << DATA_CENTER_ID_BITS) - 1));
}
this.workerId = workerId;
this.dataCenterId = dataCenterId;
}
public synchronized long nextId() {
long timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new IllegalStateException("Clock moved backwards. Refusing to generate id.");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & SEQUENCE_MASK;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - START_TIME) << 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;
}
}
```
在上述代码中,我们定义了一个SnowflakeIdGenerator类,它包含了workerId和dataCenterId两个参数,用于标识不同的节点。nextId()方法用于生成唯一的序号,它包含了以下几个步骤:
1. 获取当前时间戳,如果当前时间戳小于上一个时间戳,则表示时钟回退,抛出异常。
2. 如果当前时间戳等于上一个时间戳,则将序列号加1,如果序列号已经达到最大值,则等待下一个时间戳。
3. 如果当前时间戳大于上一个时间戳,则将序列号重置为0。
4. 将时间戳、数据中心ID、工作节点ID和序列号合并成一个64位整数返回。
这样,使用SnowflakeIdGenerator类可以生成唯一的、递增的、64位整数的序号,满足分布式系统中生成序号的需求。
阅读全文