首先实现一个实体类的基类,在基类中定义ID的生成策略,子类继承其实现,这样就不用每个实体类都去写一遍了
1.yml配置文件
#雪花算法
snowflake:
datacenter-id: 1
worker-id: 0
2.基类
import com.fasterxml.jackson.annotation.JsonFormat;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
/**
* @ClassName AbstractBaseEntity
* @Description 自定义生成ID策略的基类
* @Author mr zing
* @Date 2021/11/16 17:18
* @Version 1.1
**/
@MappedSuperclass
public abstract class AbstractBaseEntity implements Serializable {
protected String id;
/**
* 获取主键id
* @return id
* 前端js能处理的长度低于Java,防止精度丢失
*/
@Id
@GenericGenerator(name="snowFlakeIdGenerator", strategy="com.hndist.industry.config.SnowFlakeIdGenerator")
@GeneratedValue(generator="snowFlakeIdGenerator")
@JsonFormat(shape = JsonFormat.Shape.STRING)
public String getId() {
return id;
}
/**
* 设置主键id
* @param id 主键id
*/
public void setId(String id) {
this.id = id;
}
}
上述代码中,如下的注解,strategy表示生成策略实现类。
@GenericGenerator(name="snowFlakeIdGenerator", strategy="com.demo.idgenerator.SnowFlakeIdGenerator")
接下来开始编写雪花算法代码,先简单介绍下雪花算法。
SnowFlake 算法(雪花算法),是 Twitter 开源的分布式 id 生成算法。其核心思想就是:使用一个 64 bit 的 long 型的数字作为全局唯一 id。在分布式系统中的应用十分广泛,且ID 引入了时间戳,基本上保持自增。
3.自定义生成ID策略实现类
接下来实现上面的实体类基类中提到的
com.demo.idgenerator.SnowFlakeIdGenerator
类
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.annotation.PostConstruct;
import java.io.Serializable;
/**
* 雪花算法ID生成器
* @author mr ying
*/
@SuppressWarnings("all")
@Component
public class SnowFlakeIdGenerator implements IdentifierGenerator {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* 起始的时间戳
*/
private final long twepoch = 1557825652094L;
/**
* 每一部分占用的位数
*/
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long sequenceBits = 12L;
/**
* 每一部分的最大值
*/
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long maxSequence = -1L ^ (-1L << sequenceBits);
/**
* 每一部分向左的位移
*/
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampShift = sequenceBits + workerIdBits + datacenterIdBits;
@Value("${snowflake.datacenter-id:1}")
private long datacenterId; // 数据中心ID
@Value("${snowflake.worker-id:0}")
private long workerId; // 机器ID
private long sequence = 0L; // 序列号
private long lastTimestamp = -1L; // 上一次时间戳
@PostConstruct
public void init() {
String msg;
if (workerId > maxWorkerId || workerId < 0) {
msg = String.format("worker Id can't be greater than %d or less than 0", maxWorkerId);
logger.error(msg);
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
msg = String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId);
logger.error(msg);
}
}
@Transactional
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
try {
throw new Exception(String.format(
"Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
} catch (Exception e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & maxSequence;
if (sequence == 0L) {
timestamp = tilNextMillis();
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return (timestamp - twepoch) << timestampShift // 时间戳部分
| datacenterId << datacenterIdShift // 数据中心部分
| workerId << workerIdShift // 机器标识部分
| sequence; // 序列号部分
}
private long tilNextMillis() {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
//重写IdentifierGenerator的方法
@Override
public Serializable generate(SharedSessionContractImplementor session, Object o) throws HibernateException {
return String.valueOf(nextId());
}
}
主要是实现策略接口IdentifierGenerator的generate方法。
上述代码中使用@Value("${snowflake.datacenter-id:1}")
和@Value("${snowflake.worker-id:0}")
注解从环境配置中读取当前的数据中心id机器id。
使用雪花算法要注意的是,保证机器的时钟是一直增加的,也就是说不可以将时钟往前调,不然就不能保证ID的自增,并且有可能发生ID冲突(产生了重复的ID)。因此,上面的代码中,在检查到时钟异常时会抛出异常。
好的,接下来就是正常实体类继承基类就可以了,如下:
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "student", schema = "customer", catalog = "")
public class Student extends AbstractBaseEntity {
//省略属性
//省略Getter Setter
}
常见异常:出现Could not instantiate id generator
和MappingException: Could not interpret id generator strategy with custom id generator
异常,请查看@GenericGenerator(name="", strategy="")
注解中的strategy
是否指定自定义策略实现类的"完整包名"(包含类名)。
参考:
https://my.oschina.net/oldapple/blog/5189547
https://stackoverflow.com/questions/21313920/mappingexception-could-not-interpret-id-generator-strategy-with-custom-id-gener