本文分享下Spring boot項(xiàng)目下使用JPA操作數(shù)據(jù)庫時(shí)關(guān)于ID生成器的相關(guān)實(shí)現(xiàn)代碼。
在JPA中一個(gè)數(shù)據(jù)表必須要有主鍵,主鍵類型一般是推薦使用Long類型,那么在分布式微服務(wù)下需要保證ID的唯一性,此時(shí)往往需要自定義主鍵生成策略。
首先實(shí)現(xiàn)一個(gè)實(shí)體類的基類,在基類中定義ID的生成策略,子類繼承其實(shí)現(xiàn),這樣就不用每個(gè)實(shí)體類都去寫一遍了。
package com.demo.entity;
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;
/**
* @author majianzheng
*/
@MappedSuperclass
public abstract class AbstractBaseEntity implements Serializable {
protected Long id;
/**
* 獲取主鍵id
* @return id
* 前端js能處理的長(zhǎng)度低于Java,防止精度丟失
*/
@Id
@GenericGenerator(name="snowFlakeIdGenerator", strategy="com.demo.idgenerator.SnowFlakeIdGenerator")
@GeneratedValue(generator="snowFlakeIdGenerator")
@JsonFormat(shape = JsonFormat.Shape.STRING)
public Long getId() {
return id;
}
/**
* 設(shè)置主鍵id
* @param id 主鍵id
*/
public void setId(Long id) {
this.id = id;
}
}
上述代碼中,如下的注解,strategy表示生成策略實(shí)現(xiàn)類。
@GenericGenerator(name="snowFlakeIdGenerator", strategy="com.demo.idgenerator.SnowFlakeIdGenerator")
接下來開始編寫雪花算法代碼,先簡(jiǎn)單介紹下雪花算法。
SnowFlake 算法(雪花算法),是 Twitter 開源的分布式 id 生成算法。其核心思想就是:使用一個(gè) 64 bit 的 long 型的數(shù)字作為全局唯一 id。在分布式系統(tǒng)中的應(yīng)用十分廣泛,且ID 引入了時(shí)間戳,基本上保持自增。
雪花算法
接下來實(shí)現(xiàn)上面的實(shí)體類基類中提到的
com.demo.idgenerator.SnowFlakeIdGenerator 類
package com.demo.idgenerator;
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 javax.annotation.PostConstruct;
import java.io.Serializable;
/**
* 雪花算法ID生成器
* @author majianzheng
*/
@SuppressWarnings("all")
@Component
public class SnowFlakeIdGenerator implements IdentifierGenerator {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* 起始的時(shí)間戳
*/
private final long twepoch = 1557825652094L;
/**
* 每一部分占用的位數(shù)
*/
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; // 數(shù)據(jù)中心ID
@Value("${snowflake.worker-id:0}")
private long workerId; // 機(jī)器ID
private long sequence = 0L; // 序列號(hào)
private long lastTimestamp = -1L; // 上一次時(shí)間戳
@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);
}
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new Exception(String.format(
"Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & maxSequence;
if (sequence == 0L) {
timestamp = tilNextMillis();
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return (timestamp - twepoch) << timestampShift // 時(shí)間戳部分
| datacenterId << datacenterIdShift // 數(shù)據(jù)中心部分
| workerId << workerIdShift // 機(jī)器標(biāo)識(shí)部分
| sequence; // 序列號(hào)部分
}
private long tilNextMillis() {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
@Override
public Serializable generate(SharedSessionContractImplementor session, Object o) throws HibernateException {
return nextId();
}
}
主要是實(shí)現(xiàn)策略接口IdentifierGenerator的generate方法。
上述代碼中使用@Value("${snowflake.datacenter-id:1}")和@Value("${snowflake.worker-id:0}")注解從環(huán)境配置中讀取當(dāng)前的數(shù)據(jù)中心id機(jī)器id。
使用雪花算法要注意的是,保證機(jī)器的時(shí)鐘是一直增加的,也就是說不可以將時(shí)鐘往前調(diào),不然就不能保證ID的自增,并且有可能發(fā)生ID沖突(產(chǎn)生了重復(fù)的ID)。因此,上面的代碼中,在檢查到時(shí)鐘異常時(shí)會(huì)拋出異常。
好的,接下來就是正常實(shí)體類繼承基類就可以了,如下:
package com.demo.entity;
import javax.persistence.*;
/**
* @author majianzheng
*/
@Table(name = User.TABLE_NAME, uniqueConstraints = {@UniqueConstraint(columnNames = {"username"})})
@Entity
public class User extends AbstractBaseEntity {
public static final String TABLE_NAME = "demo_user";
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String userName) {
this.username = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}