栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JPA自定义ID生成策略(雪花算法)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JPA自定义ID生成策略(雪花算法)

首先实现一个实体类的基类,在基类中定义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;

@MappedSuperclass
public abstract class AbstractbaseEntity implements Serializable {
    protected String id;

    
    @Id
    @GenericGenerator(name="snowFlakeIdGenerator", strategy="com.hndist.industry.config.SnowFlakeIdGenerator")
    @GeneratedValue(generator="snowFlakeIdGenerator")
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public String getId() {
        return 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;


@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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/531520.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号