雪花算法是一种生成唯一ID的算法,常用于生成数据库主键、分布式系统中的ID等。
以下是Java代码示例:
``` public class SnowflakeIdWorker {
// 起始时间戳(毫秒)
private static final long START_STAMP = 1500000000000L;
// 机器id所占的位数
private static final long WORKER_ID_BITS = 5L;
// 数据标识id所占的位数
private static final long DATACENTER_ID_BITS = 5L;
// 支持的最大机器id(十进制),结果是31
private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
// 支持的最大数据标识id(十进制),结果是31
private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);
// 序列在id中占的位数
private static final long SEQUENCE_BITS = 12L;
// 机器ID向左移12位
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
// 数据标识id向左移17位(12+5)
private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
// 时间戳向左移22位(5+5+12)
private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
// 生成序列的掩码,这里为4095
private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
// 工作机器ID(0~31)
private long workerId;
// 数据中心ID(0~31)
private long datacenterId;
// 毫秒内序列(0~4095)
private long sequence = 0L;
// 上次生成ID的时间戳
private long lastTimestamp = -1L;
public SnowflakeIdWorker(long workerId, long