SnowFlakeGenerator生成业务键

本文介绍了如何在项目中使用SnowFlakeGenerator生成业务表的唯一键。在集群环境中,通过服务器IP计算workerId和datacenterId,确保唯一性。对于并发量不大的系统,可以使用AtomicInteger代替序列号。此外,还提及了mybatis-plus中的IdWorker,作为自定义ID生成的选项,其算法基于优化后的Twitter SnowFlake。
摘要由CSDN通过智能技术生成

 

        最近公司项目中新做一个项目,需要一个SnowFlakeGenerator用于生成业务表的唯一业务键,实际java实现如下(摘抄于网上,如有冒犯,请联系删除):

public class IdWorker{

    private long workerId;
    private long datacenterId;
    private long sequence;

    public IdWorker(long workerId, long datacenterId, long sequence){
        
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0",maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId));
        }
        System.out.printf("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d",
                time
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值