四、MyBatis-Plus雪花算法与自定义ID生成器

参考官方手册

文档中说是自3.3.0开始,默认使用雪花算法+UUID(不含中划线),我用的版本是3.4.2。

使用默认雪花算法

只需要配置entity的主键注解即可:

查看IdType源码:

ASSIGN_ID(3),
ASSIGN_UUID(4),
这里3、4分别对应官方手册的id、uuid
0是自增,1则是没有任何的规则

以admin-module微服务模块为例使用雪花算法生成ID

确保mybatis-puls的pom依赖是3.3.0以上

admin-module的yml配置

主要配置数据库:

server:
  port: 8071
spring:
  application:
    name: service-admin
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///dgut?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: root

启动类

添加mapper扫包和组件扫包,注入相关Bean:

package com.admin;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.commons.incrementer.CustomIdGenerator;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@SpringCloudApplication
@MapperScan("com.commons.school.mapper")
@ComponentScan("com.commons.school.service")
public class AdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class);
    }

    // 不可逆的密码加密类
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}

测试类

新增单个记录和多个记录测试:

package com.admin;

import com.commons.school.entity.SchoolAdmin;
import com.commons.school.mapper.SchoolAdminMapper;
import com.commons.school.service.ISchoolAdminService;
import lombok.extern.slf4j.Slf4j;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import org.junit.Assert;
import org.junit.Test;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class IdGeneratorTest {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private SchoolAdminMapper schoolAdminMapper;

    @Resource
    private ISchoolAdminService iSchoolAdminService;

    @Test
    public void test() {
        if (passwordEncoder !=null){
            String pwd = passwordEncoder.encode("yushanma");
            SchoolAdmin user = new SchoolAdmin();
            user.setUsername("shirley@163.com");
            user.setPassword(pwd);
            int result = schoolAdminMapper.insert(user);
            Assert.assertEquals(1, result);

            testBatch();
        }
    }

    /**
     * 批量插入
     */
    public void testBatch() {
        if (passwordEncoder !=null) {
            String pwd = passwordEncoder.encode("yushanma");
            List<SchoolAdmin> users = new ArrayList<>();
            for (int i = 1; i <= 10; i++) {
                SchoolAdmin user = new SchoolAdmin();
                user.setUsername("user" + i + "@163.com");
                user.setPassword(pwd);
                users.add(user);
            }
            boolean result = iSchoolAdminService.saveBatch(users);
            Assert.assertEquals(true, result);
        }
    }
}

运行测试

测试通过:

数据库新增了多个记录:

时间回退测试

如期抛出时间回退错误:

使用自定义ID生成器

ID生成算法使用Twitter的分布式自增ID算法snowflake,同样是雪花算法,这里是模拟自定义的ID生成,实际情况还要实际考虑。

参考博客 Twitter的分布式自增ID算法snowflake (Java版)

新建 SnowflakeIdWorker 类

package com.commons.idgenerator;

/**
 * Twitter_Snowflake<br>
 * SnowFlake的结构如下(每部分用-分开):<br>
 * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
 * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
 * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
 * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
 * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
 * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
 * 加起来刚好64位,为一个Long型。<br>
 * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
 */
public class SnowflakeIdWorker {

    // ==============================Fields===========================================
    /**
     * 开始时间截 2021-01-01 00:00:00
     * https://tool.lu/timestamp/
     */
    private final long twepoch = 1609430400000L;

    /**
     * 机器id所占的位数
     */
    private final long workerIdBits = 5L;

    /**
     * 数据标识id所占的位数
     */
    private final long datacenterIdBits = 5L;

    /**
     * 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
     */
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /**
     * 支持的最大数据标识id,结果是31
     */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /**
     * 序列在id中占的位数
     */
    private final long sequenceBits = 12L;

    /**
     * 机器ID向左移12位
     */
    private final long workerIdShift = sequenceBits;

    /**
     * 数据标识id向左移17位(12+5)
     */
    private final long datacenterIdShift = sequenceBits + workerIdBits;

    /**
     * 时间截向左移22位(5+5+12)
     */
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    /**
     * 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095)
     */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /**
     * 工作机器ID(0~31)
     */
    private long workerId;

    /**
     * 数据中心ID(0~31)
     */
    private long datacenterId;

    /**
     * 毫秒内序列(0~4095)
     */
    private long sequence = 0L;

    /**
     * 上次生成ID的时间截
     */
    private long lastTimestamp = -1L;

    //==============================Constructors=====================================

    /**
     * 构造函数
     *
     * @param workerId     工作ID (0~31)
     * @param datacenterId 数据中心ID (0~31)
     */
    public SnowflakeIdWorker(long workerId, long datacenterId) {
        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));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    // ==============================Methods==========================================

    /**
     * 获得下一个ID (该方法是线程安全的)
     *
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一时间生成的,则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        //时间戳改变,毫秒内序列重置
        else {
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift) //
                | (datacenterId << datacenterIdShift) //
                | (workerId << workerIdShift) //
                | sequence;
    }

    /**
     * 阻塞到下一个毫秒,直到获得新的时间戳
     *
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     *
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    //==============================Test=============================================

    /**
     * 测试
     */
    public static void main(String[] args) {
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
        for (int i = 0; i < 1000; i++) {
            long id = idWorker.nextId();
            System.out.println(Long.toBinaryString(id));
            System.out.println(id);
        }
    }
}

创建一个自定义的id生成器类实现id生成器接口,重写nextId()方法

package com.commons.incrementer;

import java.util.concurrent.atomic.AtomicLong;

import com.commons.idgenerator.SnowflakeIdWorker;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义ID生成器
 */
@Slf4j
@Component
public class CustomIdGenerator implements IdentifierGenerator {

    /**
     * workerId,机器id
     * datacenterId,数据标识id
     */
    private final SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);

    /**
     * AtomicLong是作用是对长整形进行原子操作。
     * 在32位操作系统中,64位的long 和 double 变量由于会被JVM当作两个分离的32位来进行操作,所以不具有原子性。
     * 而使用AtomicLong能让long的操作保持原子型。
     * @param entity
     * @return
     */
    @Override
    public Long nextId(Object entity) {
        //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
        String bizKey = entity.getClass().getName();
        log.info("bizKey:{}", bizKey);
        MetaObject metaObject = SystemMetaObject.forObject(entity);
//        String name = (String) metaObject.getValue("username");
        AtomicLong al = new AtomicLong(idWorker.nextId());
        final long id = al.get();
//        log.info("为{}生成主键值->:{}", name, id);
        log.info("为{}生成主键值->:{}", bizKey, id);
        return id;
    }
}

注入生成器Bean

    // 自定义id生成器
    @Bean
    public IdentifierGenerator idGenerator() {
        return new CustomIdGenerator();
    }

启动测试类

测试通过:

数据库记录:

可以看到自定义ID与默认ID的区别。

时间回退测试

修改系统时间:

运行测试:

如期抛出时钟回退错误。

腾讯文档也报错了:

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用Mybatis-Plus生成雪花算法生成id非常简单。Mybatis-Plus已经内置了雪花算法生成分布式唯一id的功能。你可以在IDEA中双击shift搜索Sequence类来查看具体的实现代码。这个类使用的就是雪花算法来生成id。关于如何在项目中使用雪花算法生成id,你可以参考CSDN上的一篇博文《mybatis-plus雪花算法增强idworker》。这篇博文详细介绍了如何在Mybatis-Plus中配置和使用雪花算法生成id。你可以按照这篇博文的步骤进行操作,非常简单易懂。总结起来,使用Mybatis-Plus生成雪花算法生成id的步骤包括建表、新建测试工程和单元测试等。在实现分析中,你可以了解到为什么Mybatis-Plus默认就是使用雪花算法来生成id。此外,你还可以通过主动设置id生成策略来使用Mybatis-Plus生成雪花算法生成idMybatis-Plus还提供了内置的雪花算法工具类IdWorker,方便你在项目中使用雪花算法生成id。希望这些信息对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [mybatis-plus雪花算法生成Id使用详解](https://blog.csdn.net/w1014074794/article/details/125604191)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

余衫马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值