-
在 pom.xml 中添加如下依赖
<!-- 引入雪花算法工具 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-captcha</artifactId> <version>5.7.20</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-core</artifactId> <version>1.1.5</version> </dependency>
-
编写雪花算法工具类
package com.future.project.util; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; public class SnowFlakeUtil { private long machineId ; private long dataCenterId ; public SnowFlakeUtil(long machineId, long dataCenterId) { this.machineId = machineId; this.dataCenterId = dataCenterId; } /** * 成员类,SnowFlakeUtil的实例对象的保存域 */ private static class IdGenHolder { private static final SnowFlakeUtil instance = new SnowFlakeUtil(); } /** * 外部调用获取SnowFlakeUtil的实例对象,确保不可变 */ public static SnowFlakeUtil get() { return IdGenHolder.instance; } /** * 初始化构造,无参构造有参函数,默认节点都是0 */ public SnowFlakeUtil() { this(0L, 0L); } private Snowflake snowflake = IdUtil.getSnowflake(machineId,dataCenterId); public synchronized long id(){ return snowflake.nextId(); } public static Long getId() { return SnowFlakeUtil.get().id(); } public static void main(String[] args) { SnowFlakeUtil snowFlakeUtil = new SnowFlakeUtil(); System.out.println(snowFlakeUtil.id()); } }
-
编写生成id规则类
package com.future.project.util; import tk.mybatis.mapper.genid.GenId; public class UUIDGenId implements GenId<String> { @Override public String genId(String table, String column) { return SnowFlakeUtil.getId().toString(); } }
-
在 主键上 使用如下方式修改主键生成方式
@Id @KeySql(genId = UUIDGenId.class) private String uuid;
08-20
2604
12-14
1384
08-30