一、雪花算法在MyBatis-Flex中的应用
MyBatis-Flex内置了高效的雪花算法主键生成器,通过简单注解即可实现分布式ID生成:
package com.example.hello.mybatisflex.snowflake.entity;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
import com.mybatisflex.core.keygen.KeyGenerators;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@Table("employee")
public class Employee {
/**
* 雪花算法主键,自动生成18位数字ID
*/
@Id(keyType = KeyType.Generator, value = KeyGenerators.flexId)
private Long id;
private String name;
private LocalDateTime createTime;
}
二、官方文档
@Id注解
内置主键生成器
三、项目创建与配置
1. 创建项目
2. Maven依赖配置(POM)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.0</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>hello-mybatis-flex-snowflake</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hello-mybatis-flex-snowflake</name>
<description>mybatis-flex 雪花算法ID</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring-boot3-starter</artifactId>
<version>1.10.9</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. 数据库配置(application.yml)
spring:
application:
name: hello-mybatis-flex-snowflake
datasource:
url: jdbc:mysql://localhost:3306/flex_test
username: flex_test_user
password: 12345678
4. EmployeeMapper
package com.example.hello.mybatisflex.snowflake.mapper;
import com.example.hello.mybatisflex.snowflake.entity.Employee;
import com.mybatisflex.core.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {
}
四、使用示例与数据效果
1. 数据插入代码
package com.example.hello.mybatisflex.snowflake;
import com.example.hello.mybatisflex.snowflake.entity.Employee;
import com.example.hello.mybatisflex.snowflake.mapper.EmployeeMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDateTime;
@Slf4j
@SpringBootTest
class EmployeeTest {
@Autowired
private EmployeeMapper employeeMapper;
@Test
void insert() {
Employee employee = new Employee();
employee.setName("张三");
employee.setCreateTime(LocalDateTime.now());
employeeMapper.insert(employee);
}
}
2. 数据库结果
id | name | create_time |
---|---|---|
292200305679462400 | 张三 | 2025-06-16 20:40:42 |
五、18位ID的生成原理
为什么 MyBatis-Flex 使用雪花算法生成的ID是18位数字?
使用MyBatisPlus
的雪花算法生成的主键都是19位的数字。
1. 与MyBatisPlus的差异
- MyBatis-Flex:生成18位数字ID(如
292200305679462400
) - MyBatisPlus:生成19位数字ID
2. 核心原因:时间起始点
MyBatis-Flex的雪花算法ID生成器中,使用自定义的起始时间戳(2023-04-02 13:01:00):
/**
* 时间起始标记点,一旦确定不能变动(2023-04-02 13:01:00)。
*/
private static long twepoch = 1680411660000L;
MyBatis-Flex SnowFlakeIDKeyGenerator 源代码
3. ID结构解析
雪花算法的64位ID由以下四部分组成:
1. 符号位(1位):固定为0,保证ID为正数。
2. 时间戳(41位):精确到毫秒级,支持约69年的时间范围(从算法起始时间计算)。
3. 机器ID(10位):可细分为数据中心ID(5位)和工作机器ID(5位),最多支持1024个节点。
4. 序列号(12位):同一毫秒内可生成4096个唯一ID,解决并发冲突。
4. 时间戳计算验证
package com.example.hello.mybatisflex.snowflake;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/**
* 为测试雪花算法ID,需要计算时间戳的实际时间,将时间戳转化为日期时间
*/
@Slf4j
public class TimestampConversionTest {
/**
* 测试时间戳到日期时间的转换逻辑
*
* <p>验证三种时间戳转换方式:
* 1. 转换为 Instant(UTC 时间)
* 2. 转换为带时区的 ZonedDateTime(系统默认时区)
* 3. 转换为本地日期时间 LocalDateTime(无时区信息)
*
* <p>使用固定时间戳:1680411660000L + 69665981693L = 1750077641693L,对应北京时间:2025-06-16 20:40:41.693
*/
@Test
void testTimestampToDateTimeConversion() {
// 固定测试时间戳(毫秒)
long testTimestamp = 1680411660000L + 69665981693L;
log.info("测试时间戳: {} ms", testTimestamp);
// 1. 转换为 Instant (UTC 时间)
Instant utcInstant = Instant.ofEpochMilli(testTimestamp);
log.info("UTC 标准时间: {}", utcInstant);
// 2. 转换为带时区的日期时间(使用系统默认时区)
ZoneId systemZone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = utcInstant.atZone(systemZone);
log.info("带时区时间 [{}]: {}", systemZone, zonedDateTime);
// 3. 转换为本地日期时间(无时区信息)
LocalDateTime localDateTime = LocalDateTime.ofInstant(utcInstant, systemZone);
log.info("本地日期时间: {}", localDateTime);
// 4. 格式化输出(可选)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss.SSS");
log.info("格式化输出: {}", localDateTime.format(formatter));
}
}
输出结果:
02:50:21.455 [main] INFO com.example.hello.mybatisflex.snowflake.TimestampConversionTest -- 测试时间戳: 1750077641693 ms
02:50:21.470 [main] INFO com.example.hello.mybatisflex.snowflake.TimestampConversionTest -- UTC 标准时间: 2025-06-16T12:40:41.693Z
02:50:21.470 [main] INFO com.example.hello.mybatisflex.snowflake.TimestampConversionTest -- 带时区时间 [GMT+08:00]: 2025-06-16T20:40:41.693+08:00[GMT+08:00]
02:50:21.471 [main] INFO com.example.hello.mybatisflex.snowflake.TimestampConversionTest -- 本地日期时间: 2025-06-16T20:40:41.693
02:50:21.473 [main] INFO com.example.hello.mybatisflex.snowflake.TimestampConversionTest -- 格式化输出: 2025年06月16日 20:40:41.693
MyBatis-Flex 通过雪花算法(SnowFlakeIDKeyGenerator)生成数据库主键,生成的主键是18位数字。
插入MySQL数据库中的雪花算法生成的主键(292200305679462400
):
如果使用“时间起始标记点”,经过验算ID反向解析出的时间戳能够和生成这个ID的时间对上:
292200305679462400(十进制) = 010000001110000110101010000100111111010010001111000000000000(二进制)
获取“时间戳”部分:
1000000111000011010101000010011111101(二进制) = 69665981693(十进制)
时间起始标记点+“时间戳”部分
1680411660000 + 69665981693 = 1750077641693 = 2025-06-16 20:40:41(转换为北京时间)
graph LR
A[雪花算法ID] --> B[18位设计]
B --> C[符号位(1位)]
B --> D[时间戳偏移量]
B --> E[10位机器ID]
B --> F[12位序列号]
D --> H[1000000111000011010101000010011111101]
E --> I[1024个节点]
F --> J[4096/ms并发]
猜测: 实现雪花算法时,为了减少存储位数,没有直接使用时间戳,而是使用了时间戳和【2023-04-02 13:01:00】的偏移量。