雪花算法
SnowflakeIdGenerator
标准雪花算法生成器,实现 MyBatis-Plus IdentifierGenerator
SnowflakeIdGenerator
SnowflakeIdGenerator 位于 com.xlf.utility.incrementer,是标准雪花算法核心实现。
它实现了 MyBatis-Plus 的 IdentifierGenerator 接口,核心生成方法为 nextId(Object entity)。
类定义
package com.xlf.utility.incrementer;
public class SnowflakeIdGenerator implements IdentifierGenerator {
public SnowflakeIdGenerator() {}
public SnowflakeIdGenerator(long datacenterId, long machineId) {
configure(datacenterId, machineId);
}
public SnowflakeIdGenerator(long datacenterId, long machineId, long epoch) {
this.epoch = epoch;
configure(datacenterId, machineId);
}
public void configure(long datacenterId, long machineId) { ... }
@Override
public Number nextId(Object entity) { ... }
@Override
public String nextUUID(Object entity) { ... }
}参数与范围
字段
类型
关键行为
- 生成方法使用内部
lock同步,保证并发安全。 - 同毫秒内序列号自增,溢出后自旋等待下一毫秒。
- 检测到时钟回拨时,会抛出
BusinessException(SERVER_INTERNAL_ERROR)。 - 未调用
configure(...)就生成 ID,也会抛BusinessException。
使用示例
手动创建并生成
import com.xlf.utility.incrementer.SnowflakeIdGenerator;
SnowflakeIdGenerator generator = new SnowflakeIdGenerator(1, 1, 1690214400000L);
Long id = (Long) generator.nextId(null);
String idString = generator.nextUUID(null);默认构造 + configure
SnowflakeIdGenerator generator = new SnowflakeIdGenerator();
generator.configure(2, 10);
Long id = (Long) generator.nextId(null);与 SnowflakeUtil 的关系
SnowflakeUtil 是该生成器的静态门面。
业务层通常直接用 SnowflakeUtil.generateId();只有自定义初始化流程时才直接操作生成器。