news 2026/6/10 18:12:40

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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; } }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/10 10:20:10

智能Agent容器内存溢出怎么办?深入解读资源限制配置最佳实践

第一章&#xff1a;智能Agent容器内存溢出问题的根源剖析智能Agent在现代分布式系统中承担着任务调度、状态监控与自主决策等关键职能。当这些Agent以容器化形式部署时&#xff0c;内存资源受限于容器运行时的配置策略&#xff0c;极易因内存管理不当引发溢出&#xff08;OOM, …

作者头像 李华
网站建设 2026/6/10 14:09:05

MOS管的雪崩击穿

目录 简介 分析 关于雪崩击穿 热击穿 寄生晶体管引起的当前破坏 简介 当MOSFET关断时&#xff0c;若漏极与源极之间的施加电压超过绝对最大额定值VDSS&#xff0c;就会发生雪崩击穿。即使漏极的直流电压在额定范围内&#xff0c;由于布线中的寄生电感等因素&#xff0c;可…

作者头像 李华
网站建设 2026/6/10 12:53:55

为什么顶尖机构都在用R做生态评估?3个真实案例揭示其不可替代性

第一章&#xff1a;环境监测的 R 语言生态风险评估在环境科学领域&#xff0c;R 语言已成为生态风险评估的核心工具之一。其强大的统计建模能力与丰富的地理空间分析包&#xff08;如 sp, sf, raster&#xff09;相结合&#xff0c;为环境监测数据的处理、可视化和风险推断提供…

作者头像 李华
网站建设 2026/6/10 12:53:12

Agent服务升级总出错?立即检查这4个Docker数据卷挂载配置点

第一章&#xff1a;Agent服务的Docker数据卷挂载概述在构建基于容器的Agent服务时&#xff0c;持久化存储是保障服务状态和配置一致性的关键环节。Docker数据卷&#xff08;Volume&#xff09;提供了一种高效、安全的方式&#xff0c;用于在主机与容器之间或多个容器之间共享和…

作者头像 李华
网站建设 2026/6/10 15:24:26

量子计算瓶颈如何破?R语言带你实现电路优化的指数级加速

第一章&#xff1a;量子计算瓶颈如何破&#xff1f;R语言带你实现电路优化的指数级加速在当前量子计算的发展中&#xff0c;量子门电路的深度和复杂性成为制约实际应用的核心瓶颈。过深的电路不仅增加噪声影响&#xff0c;还显著降低计算保真度。借助R语言强大的数值优化与图结…

作者头像 李华
网站建设 2026/6/10 12:55:06

【Dify 1.7.0升级必看】:音频降噪算法全面进化,企业级语音应用新标准

第一章&#xff1a;Dify 1.7.0音频降噪处理Dify 1.7.0 引入了全新的音频预处理模块&#xff0c;支持在语音输入场景中实现实时降噪处理。该功能特别适用于智能客服、语音助手等对环境噪声敏感的应用场景&#xff0c;通过深度学习模型有效分离人声与背景噪音&#xff0c;提升语音…

作者头像 李华