JAVA实现雪花算法生成唯一订单号工具类的方法
发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,这篇文章主要讲解了"JAVA实现雪花算法生成唯一订单号工具类的方法",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"JAVA实现雪花算法生成唯一订单号工具
千家信息网最后更新 2025年12月02日JAVA实现雪花算法生成唯一订单号工具类的方法
这篇文章主要讲解了"JAVA实现雪花算法生成唯一订单号工具类的方法",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"JAVA实现雪花算法生成唯一订单号工具类的方法"吧!
import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import java.util.Calendar;/** * Default distributed primary key generator. * ** Use snowflake algorithm. Length is 64 bit. *
* ** 1bit sign bit. * 41bits timestamp offset from 2016.11.01(ShardingSphere distributed primary key published data) to now. * 10bits worker process id. * 12bits auto increment offset in one mills ** ** Call @{@code DefaultKeyGenerator.setWorkerId} to set worker id, default value is 0. *
* ** Call @{@code DefaultKeyGenerator.setMaxTolerateTimeDifferenceMilliseconds} to set max tolerate time difference milliseconds, default value is 0. *
* * @author gaohongtao */@Slf4jpublic final class SnowflakeKeyGenerator { public static final long EPOCH; private static final long SEQUENCE_BITS = 12L; private static final long WORKER_ID_BITS = 10L; private static final long SEQUENCE_MASK = (1 << SEQUENCE_BITS) - 1; private static final long WORKER_ID_LEFT_SHIFT_BITS = SEQUENCE_BITS; private static final long TIMESTAMP_LEFT_SHIFT_BITS = WORKER_ID_LEFT_SHIFT_BITS + WORKER_ID_BITS; private static final long WORKER_ID_MAX_VALUE = 1L << WORKER_ID_BITS; private static long workerId; private static int maxTolerateTimeDifferenceMilliseconds = 10; static { Calendar calendar = Calendar.getInstance(); calendar.set(2016, Calendar.NOVEMBER, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); EPOCH = calendar.getTimeInMillis(); } private byte sequenceOffset; private long sequence; private long lastMilliseconds; /** * Set work process id. * * @param workerId work process id */ public static void setWorkerId(final long workerId) { if (workerId < 0L || workerId >= WORKER_ID_MAX_VALUE) { throw new IllegalArgumentException(); } SnowflakeKeyGenerator.workerId = workerId; } /** * Set max tolerate time difference milliseconds. * * @param maxTolerateTimeDifferenceMilliseconds max tolerate time difference milliseconds */ public static void setMaxTolerateTimeDifferenceMilliseconds(final int maxTolerateTimeDifferenceMilliseconds) { SnowflakeKeyGenerator.maxTolerateTimeDifferenceMilliseconds = maxTolerateTimeDifferenceMilliseconds; } /** * Generate key. * * @return key type is @{@link Long}. */ public synchronized Long generateKey() { long currentMilliseconds = System.currentTimeMillis(); if (waitTolerateTimeDifferenceIfNeed(currentMilliseconds)) { currentMilliseconds = System.currentTimeMillis(); } if (lastMilliseconds == currentMilliseconds) { if (0L == (sequence = (sequence + 1) & SEQUENCE_MASK)) { currentMilliseconds = waitUntilNextTime(currentMilliseconds); } } else { vibrateSequenceOffset(); sequence = sequenceOffset; } lastMilliseconds = currentMilliseconds; return ((currentMilliseconds - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (workerId << WORKER_ID_LEFT_SHIFT_BITS) | sequence; } @SneakyThrows private boolean waitTolerateTimeDifferenceIfNeed(final long currentMilliseconds) { if (lastMilliseconds <= currentMilliseconds) { return false; } long timeDifferenceMilliseconds = lastMilliseconds - currentMilliseconds; if (timeDifferenceMilliseconds >= maxTolerateTimeDifferenceMilliseconds) { log.error(String.format("Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", lastMilliseconds, currentMilliseconds)); //throw new IllegalStateException(String.format("Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", lastMilliseconds, currentMilliseconds)); } Thread.sleep(timeDifferenceMilliseconds); return true; } private long waitUntilNextTime(final long lastTime) { long result = System.currentTimeMillis(); while (result <= lastTime) { result = System.currentTimeMillis(); } return result; } private void vibrateSequenceOffset() { sequenceOffset = (byte) (~sequenceOffset & 1); }}
spring boot配置文件:
keyGenerator: snowflake: workerId: 20 #进程ID,每个实例都要设置不同的值,范围:0-1023 maxTolerateTime: 1500 #最大容忍时钟回退时间,单位:毫秒
如果mybati使用了plugins插件,可以继承进来
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.transaction.annotation.EnableTransactionManagement;@EnableTransactionManagement@Configuration@MapperScan({"com.csair.module.*.mybatis.mapper"})public class MybatisPlusConfiguration { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } @Bean public SnowflakeKeyGenerator getSnowflakeKeyGenerator(@Value("${keyGenerator.snowflake.workerId}")Integer workerId, @Value("${keyGenerator.snowflake.maxTolerateTime}")Integer maxTolerateTime){ SnowflakeKeyGenerator.setWorkerId(workerId); SnowflakeKeyGenerator.setMaxTolerateTimeDifferenceMilliseconds(maxTolerateTime); return new SnowflakeKeyGenerator(); }}感谢各位的阅读,以上就是"JAVA实现雪花算法生成唯一订单号工具类的方法"的内容了,经过本文的学习后,相信大家对JAVA实现雪花算法生成唯一订单号工具类的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
工具
方法
算法
订单
订单号
雪花
生成
学习
内容
不同
最大
单位
实例
就是
思路
情况
插件
文件
文章
时钟
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
云服务器怎么看已开放
高防网站服务器租用
公安网络安全调研文章范文
编译系统属于软件开发工具吗
vpn服务器地址怎么弄
服务器开机卡在系统初始化
服务器的市场大不大
科技创新与互联网经济
软件开发 编码阶段流程图
2022年魔兽世界怀旧服服务器
药智数据 原药智网数据库
数据库怎么取消重复项
服务器都用什么系统
软件开发公司成本费用体系
怎样应对网络安全人才短缺
县教育局网络安全责任书
航空购票系统数据库
职业学校计算机网络技术
监狱网络安全管理体检要求
软件开发前景
财务软件开发建议有哪些
流浪者柯南游戏服务器
家庭云服务器安全吗
共享服务器怎么恢复
网络安全密钥怎么关闭
国产数据库技术路线
苹果手机服务器关闭了吗
服务器托管公司
自考计算机网络技术张海霞
惠普服务器优势