写一个雪花算法java代码案例
时间: 2023-09-21 07:05:59 浏览: 121
雪花算法java版实现
5星 · 资源好评率100%
### 回答1:
```java
public class Snowflake {
// 起始的时间戳
private final static long START_STMP = 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 TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心
private long machineId; //机器标识
private long sequence = 0L; //序列号
private long lastStmp = -1L;//上一次时间戳
public Snowflake(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
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
}``
### 回答2:
雪花算法(Snowflake)是一种分布式唯一ID生成算法,通常用于解决分布式系统中产生唯一ID的需求。下面是一个简单的雪花算法的Java代码案例:
```java
public class Snowflake {
private final long startTime; // 起始时间戳,可以根据实际需要进行调整
private long dataCenterId; // 数据中心ID
private long workerId; // 工作机器ID
private long sequence = 0L; // 序列号
private final long dataCenterIdBits = 5L; // 数据中心ID所占位数
private final long workerIdBits = 5L; // 工作机器ID所占位数
private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits); // 最大数据中心ID
private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 最大工作机器ID
private final long sequenceBits = 12L; // 序列号所占位数
private final long workerIdShift = sequenceBits; // 工作机器ID左移位数
private final long dataCenterIdShift = sequenceBits + workerIdBits; // 数据中心ID左移位数
private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits; //时间戳左移位数
private long lastTimestamp = -1L;
public Snowflake(long dataCenterId, long workerId) {
if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
throw new IllegalArgumentException("数据中心ID超出范围");
}
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException("工作机器ID超出范围");
}
this.dataCenterId = dataCenterId;
this.workerId = workerId;
this.startTime = System.currentTimeMillis();
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException("时钟回拨异常");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & ((1 << sequenceBits) - 1);
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - startTime) << timestampLeftShift)
| (dataCenterId << dataCenterIdShift)
| (workerId << workerIdShift)
| sequence;
}
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
protected long timeGen() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
Snowflake snowflake = new Snowflake(1, 1);
for (int i = 0; i < 10; i++) {
long id = snowflake.nextId();
System.out.println(id);
}
}
}
```
这段代码实现了一个Java版本的雪花算法,主要包括:
- Snowflake类是雪花算法的核心类,其中定义了一些常量和变量。
- 构造函数Snowflake(dataCenterId, workerId)用于初始化数据中心ID和工作机器ID。
- nextId()方法用于生成唯一ID,它首先获取当前时间戳,然后根据时间戳和其他信息生成ID。在同一毫秒内生成的ID会带有自增的序列号,确保每个ID都是唯一的。
- tilNextMillis(lastTimestamp)方法用于处理时钟回拨异常,即在同一毫秒内生成的ID超过了序列号的最大值。
- timeGen()方法用于获取当前时间戳。
- main()方法是一个简单的示例,生成10个ID并打印输出。
这个代码案例可以通过创建Snowflake对象,然后调用nextId()方法来生成唯一ID。每个Snowflake对象有独立的数据中心ID和工作机器ID,以保证在分布式系统中生成全局唯一的ID。
### 回答3:
雪花算法(Snowflake)是一种基于时间戳、机器ID和序列号生成唯一ID的算法。它的核心思想是在分布式系统中生成ID,保证每个ID是唯一且有序的。
下面是一个简单的雪花算法的Java代码案例:
```java
public class SnowflakeIdGenerator {
// 初始时间戳,可以根据需要修改
private final static long START_TIMESTAMP = 1593837600000L;
// 机器ID所占的位数
private final static long WORKER_ID_BITS = 5L;
// 数据中心ID所占的位数
private final static long DATA_CENTER_ID_BITS = 5L;
// 支持的最大机器ID,结果是31
private final static long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS);
// 支持的最大数据中心ID,结果是31
private final static long MAX_DATA_CENTER_ID = -1L ^ (-1L << DATA_CENTER_ID_BITS);
// 序列号所占的位数
private final static long SEQUENCE_BITS = 12L;
// 机器ID左移12位
private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
// 数据中心ID左移17位
private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
// 时间戳左移22位
private final static long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;
// 序列号的最大值,结果是4095
private final static long MAX_SEQUENCE = -1L ^ (-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 > MAX_WORKER_ID || workerId < 0) {
throw new IllegalArgumentException("workerId can't be greater than MAX_WORKER_ID or less than 0");
}
if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
throw new IllegalArgumentException("dataCenterId can't be greater than MAX_DATA_CENTER_ID or less than 0");
}
this.workerId = workerId;
this.dataCenterId = dataCenterId;
}
public synchronized long nextId() {
long timestamp = timeGen();
// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过,抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id.");
}
// 如果当前时间与上一次ID生成的时间戳相同,需要使用序列号进行区分
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
// 如果序列号为0,则需要重新获取时间戳
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else { // 时间戳改变,序列号重置为0
sequence = 0L;
}
lastTimestamp = timestamp;
// 生成最终的ID,并返回
return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
| (dataCenterId << DATA_CENTER_ID_SHIFT)
| (workerId << WORKER_ID_SHIFT)
| sequence;
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
long id = idGenerator.nextId();
System.out.println("生成的ID:" + id);
}
}
```
这个雪花算法的实现中,包含了时间戳、机器ID、数据中心ID和序列号等概念。通过调用 `nextId` 方法可以生成唯一且有序的ID。在示例中,创建了一个 `SnowflakeIdGenerator` 对象,并设置了机器ID和数据中心ID为1,然后调用 `nextId` 方法生成ID并打印输出。
阅读全文