java 雪花算法工具类
时间: 2024-06-08 07:03:51 浏览: 266
雪花算法是Twitter开源的分布式ID生成算法,它可以保证在分布式环境中生成全局唯一的ID。Java中也有相应的雪花算法工具类,常见的有Snowflake和Leaf。
其中,Snowflake是一个比较常用的Java雪花算法工具类,其生成的ID有64位,其中第1个bit是无用的,接下来的41个bit表示时间戳(精确到毫秒级别),5个bit表示数据中心ID,5个bit表示机器ID,最后12个bit表示序列号。Snowflake算法工具类需要传入两个参数:数据中心ID和机器ID,这两个参数需要根据具体的业务场景进行设置。
以下是Snowflake算法工具类的示例代码:
```java
public class SnowflakeIdGenerator {
// 起始的时间戳
private final static long START_STAMP = 1480166465631L;
// 每一部分占用的位数
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 ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-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; // 数据中心
private long machineId; // 机器标识
private long sequence = 0L; // 序列号
private long lastStamp = -1L; // 上一次时间戳
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;
}
public synchronized long nextId() {
long currStamp = getNewStamp();
if (currStamp < lastStamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStamp == lastStamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0L) {
currStamp = getNextMill();
}
} else {
sequence = 0L;
}
lastStamp = currStamp;
return (currStamp - START_STAMP) << TIMESTAMP_LEFT
| datacenterId << DATACENTER_LEFT
| machineId << MACHINE_LEFT
| sequence;
}
private long getNextMill() {
long mill = getNewStamp();
while (mill <= lastStamp) {
mill = getNewStamp();
}
return mill;
}
private long getNewStamp() {
return System.currentTimeMillis();
}
}
```
阅读全文