当前位置: 首页 > news >正文

java使用Redison自旋锁和mysql生成唯一编号

1. 数据库表设计(存储递增基准值)

CREATE TABLE `t_sequence` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `type_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '关键字段', `rule_date` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '规则日期', `max_number` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '自增序列号', `version` bigint(20) DEFAULT NULL COMMENT '版本号', `deleted` varchar(1) COLLATE utf8mb4_unicode_ci DEFAULT '0' COMMENT '删除状态:0-正常 1-删除', `create_user_id` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `create_time` datetime DEFAULT CURRENT_TIMESTAMP, `update_user_id` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `update_time` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='序列表';

2、生成实体

@Getter @Setter @Accessors(chain = true) @TableName("t_sequence") @ApiModel(value = "TSequence对象", description = "序列表") public class TSequence implements Serializable { @ApiModelProperty("主键ID") @TableId(value = "id", type = IdType.AUTO) private Long id; @ApiModelProperty("关键字段") private String typeKey; @ApiModelProperty("规则日期") private String ruleDate; @ApiModelProperty("对应某年的自增序列号") private String maxNumber; @ApiModelProperty("版本号") private Long version; @ApiModelProperty("创建人ID") private Long createUserId; @ApiModelProperty("创建时间") private LocalDateTime createTime; @ApiModelProperty("更新人ID") private Long updateUserId; @ApiModelProperty("更新时间") private LocalDateTime updateTime; @ApiModelProperty("是否删除:0-未删除 1-已删除") private String deleted; }

3、实现业务

@Component @AllArgsConstructor @Log4j2 public class TSequenceService { private final RedissonClient redissonClient; private final TSequenceMapper sequenceMapper; private static final String ORDER_SEQ_LOCK_KEY = "seq:lock:";//锁前缀 private static final int MAX_RETRY_TIMES = 10;//自旋次数 private static final long RETRY_INTERVAL = 200;//自旋一次等待时间 private static final long LOCK_EXPIRE_SECONDS = 30;//锁等待时间 /** * 生成唯一编码 * @param prefix :前缀 * @param typeKey :业务类型 * @param currentValue :自增数据 * @return */ @Transactional(rollbackFor = Exception.class) public String publicCreateNumber(String prefix,String typeKey,String currentValue) { String lockKey = ORDER_SEQ_LOCK_KEY + typeKey; int retryCount = 0; // 锁对象移到循环外,避免重复创建 RLock lock = redissonClient.getLock(lockKey); // 自旋获取锁 while (retryCount < MAX_RETRY_TIMES) { try { // 尝试获取锁(非阻塞) boolean locked = lock.tryLock(0, LOCK_EXPIRE_SECONDS, TimeUnit.SECONDS); if (locked) { try { // 加锁成功后执行核心逻辑 return doCreateNumber(prefix,typeKey,currentValue); } finally { // 释放锁(确保当前线程持有锁) if (lock.isHeldByCurrentThread()) { lock.unlock(); log.info("释放分布式锁成功,lockKey:{}", lockKey); } } } else { // 自旋等待 retryCount++; log.warn("第{}次获取锁失败,等待{}ms后重试,lockKey:{}", retryCount, RETRY_INTERVAL, lockKey); TimeUnit.MILLISECONDS.sleep(RETRY_INTERVAL); } } catch (InterruptedException e) { log.error("自旋等待时被中断", e); Thread.currentThread().interrupt(); throw new RuntimeException("生成编号失败:线程被中断"); } catch (Exception e) { log.error("获取/释放锁异常", e); throw new RuntimeException("生成编号失败:锁操作异常", e); } } log.error("生成编号失败:超出最大自旋重试次数({}次),lockKey:{}", MAX_RETRY_TIMES, lockKey); throw new RuntimeException("业务繁忙,请稍后尝试"); } /** * 加锁后的核心业务逻辑 * @param prefix :前缀 * @param typeKey :业务类型 * @param currentValue :自增数据 * @return */ public String doCreateNumber(String prefix,String typeKey,String currentValue) { String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));//获取日期 long newVersion; int nextNumber; String number; //查询数据库序列数据,悲观锁查询,锁定行 TSequence tSequence = sequenceMapper.selectOne(new LambdaQueryWrapper<TSequence>() .eq(TSequence::getDeleted, DeletedEnum.DEFAULT.getValue()) .eq(TSequence::getTypeKey, typeKey) .eq(TSequence::getRuleDate, yearMonth) .last("FOR UPDATE")); if (ObjectUtil.isNull(tSequence)) { // 初始化编号 nextNumber = Integer.parseInt(currentValue)+ 1; // 使用 DecimalFormat 保持前导零 DecimalFormat df = new DecimalFormat(currentValue); String index = df.format(nextNumber); number = prefix+yearMonth+index;//拼接新编号 // 插入新记录 TSequence newSequence = new TSequence(); newSequence.setTypeKey(typeKey); newSequence.setMaxNumber(nextNumber); newSequence.setVersion(1L); newSequence.setRuleDate(yearMonth); newSequence.setCreateTime(LocalDateTime.now()); int insert = sequenceMapper.insert(newSequence); if (insert != 1) { throw new RuntimeException("初始化序列失败,enumValue:" + typeKey); } log.info("初始化序列成功,编号:{}", number); } else { // 已有序列,递增编号 String maxNumber = tSequence.getMaxNumber(); nextNumber = Integer.parseInt(tSequence.getMaxNumber())+ 1; // 使用 DecimalFormat 保持前导零 DecimalFormat df = new DecimalFormat(currentValue); String index = df.format(nextNumber); number = prefix+yearMonth+index;//拼接新编号 if (ObjectUtil.isEmpty(number)) { throw new RuntimeException("递增编号失败,当前最大编号:" + maxNumber); } // 乐观锁更新:校验旧版本号,设置新版本号 Long oldVersion = tSequence.getVersion(); newVersion = oldVersion + 1; LambdaUpdateWrapper<TSequence> updateWrapper = new LambdaUpdateWrapper<TSequence>() .eq(TSequence::getTypeKey, typeKey) .eq(TSequence::getRuleDate, yearMonth) .eq(TSequence::getMaxNumber, maxNumber) // 校验旧编号 .eq(TSequence::getVersion, oldVersion) // 校验旧版本号(核心修复) .set(TSequence::getVersion, newVersion) // 设置新版本号 .set(TSequence::getMaxNumber, nextNumber) .set(TSequence::getUpdateTime, LocalDateTime.now()); // 执行更新并校验结果 int update = sequenceMapper.update(null, updateWrapper); if (update != 1) { throw new RuntimeException("更新序列失败,并发冲突!enumValue:" + typeKey + ", 当前编号:" + maxNumber); } log.info("更新序列成功,旧编号:{},新编号:{}", maxNumber, number); } return number; } }
http://www.cnnetsun.cn/news/90804.html

相关文章:

  • AI元人文构想:人机协作的“未来哪吒”架构
  • Qwen-Image:突破文本渲染与编辑的视觉生成模型
  • 四年累销600万,这就是“海洋速度”
  • Keras与TensorFlow-GPU配置避坑指南
  • Redis + ThinkPHP 实战学习手册(含秒杀场景)
  • 展锐平台:修复使用触控笔主动橡皮擦键功能时, InputDispatcher 发生了致命错误(F 级别),导致 system_server 进程崩溃并重启。
  • EmotiVoice:支持多情感的开源TTS引擎
  • LobeChat能否部署在Netlify?静态站点托管进阶用法
  • 倒计时 5 天!GOBI 2025 全球开源商业创新大会全日程发布,附参会指南!
  • Docker Offload优先级机制详解:90%工程师忽略的关键参数
  • 【Dify高性能视频处理指南】:精准帧率设置提升提取速度300%
  • 为什么你的Tesseract在Dify中处理慢?这5个批量优化关键点必须掌握
  • CDM(充电器件模型)导致芯片失效原因
  • IL-2:调控免疫稳态的“双面因子”
  • 【环境风险评估效能革命】:基于R语言的动态监测系统搭建实录
  • 揭秘Dify中PDF加密与权限验证机制:企业级数据防护必备技能
  • 酒精饮料市场:挑战中寻找机遇 eBest
  • 为什么顶尖数据团队都在用R Shiny做多模态报告?真相令人震惊
  • ChatTTS与GPT-SoVITS语音合成对比分析
  • MySQL Shell 使用方法
  • Docker多阶段构建与精简基础镜像(边缘Agent瘦身必看)
  • PPIO上线阿里Wan 2.6:制作电影级AI视频,对标Sora2
  • 【混合检索的Dify结果融合】:揭秘高效信息聚合背后的黑科技
  • 从零搭建高效音频流水线:Dify 1.7.0切片配置完整教程
  • 大数据ETL中的数据质量提升工具与方法
  • 筑巢引凤 - Ascend C开发环境极速部署与验证全攻略
  • 模型训练中的精度保障:Ascend C算子数值稳定性分析
  • 【金融风险对冲实战指南】:掌握R语言在投资组合风险管理中的7大核心技巧
  • 空间转录组批次校正实战指南(R语言完整代码+案例解析)
  • 计算机毕业设计附项目源码帮做/Java管理系统/springboot网站/深度学习/神经网络算法/yolo图像识别/从选题到部署,一篇搞定!