参考官方手册

文档中说是自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的区别。

时间回退测试

修改系统时间:

运行测试:

如期抛出时钟回退错误。

腾讯文档也报错了:

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐