图片预览

滚轮缩放 · 拖动移动 · Esc 关闭

Skip to content

请求幂等 ​

当前实现内容可在当前源码中定位并复现
适用范围
muotai-common-idempotent 的接入与维护
阅读对象
后端开发、测试和运维
源码基线
muotai-backend 提交 a08dae999(muotai-common 5.8.0)
源文件
muotai-backend/muotai-common/muotai-common-idempotent/
核对日期
2026-11-28

作用与提供的能力 ​

muotai-common-idempotent 基于 Redisson 的分布式 RMapCache(固定缓存键 idempotent)为标注 @Idempotent 的 Servlet 接口提供限时防重提交能力,拦截短时间内的重复请求并抛出 IdempotentException。

接入与使用 ​

在业务模块的 pom.xml 中加入 com.aroundix:muotai-common-idempotent(同仓库子模块沿用父 POM 版本):

  1. 确保应用已配置可用的 Redisson/Redis 连接,并在统一异常处理器中映射 IdempotentException。
  2. 在需要防重的 Controller 方法上标注 @Idempotent,推荐通过 key 编写包含业务标识 + 用户/租户标识的 SpEL 表达式;未填 key 时默认拼接 request.getRequestURI() + Arrays.asList(joinPoint.getArgs())。
  3. 合理设置 expireTime(默认 1,单位 TimeUnit.SECONDS)与 delKey(默认 false:窗口内持续防重;设为 true 则方法执行完立即移除键,允许再次提交)。

最小示例 ​

java
@Idempotent(
    key = "#request.orderNo",
    expireTime = 30,
    timeUnit = TimeUnit.SECONDS,
    info = "订单正在处理,请勿重复提交"
)
@PostMapping("/orders")
public R<?> submit(@RequestBody OrderRequest request) {
    return orderService.submit(request);
}

幂等切面执行与清理时序 ​

IdempotentAspect 通过 @Before 与 @After 两个增强点与 THREAD_CACHE 线程变量协作,完整执行链路如下:

@Idempotent 幂等键解析、Redisson RMapCache 校验与后置清理链路1 / 4
HTTP 请求
IdempotentAspect
Redisson RMapCache
业务方法
1
解析幂等 Key
HTTP 请求 → IdempotentAspect

@Before 获取当前 HttpServletRequest 与 @Idempotent 注解:若配置了 key,交由 KeyResolver 解析 SpEL;否则以 requestURI + args.toString() 拼接默认 Key。

配置与装配速查 ​

项目当前源码入口
装配方式自动配置(装配 IdempotentAspect 与 KeyResolver)+ @Idempotent
注解参数key(SpEL,空则用 URI+参数列表)、expireTime(默认 1)、timeUnit(默认秒)、info(提示文案)、delKey(默认 false)
Redisson 缓存键固定 RMapCache 名称:idempotent
外部前提可用的 Redisson/Redis 实例、Servlet HTTP 请求上下文(RequestContextHolder)

代码组织 ​

  • idempotent/annotation/:@Idempotent 注解参数定义。
  • idempotent/aspect/:IdempotentAspect(@Before 校验写入、@After 按 delKey 删除并清理 THREAD_CACHE)。
  • idempotent/expression/:KeyResolver 解析 SpEL 幂等键。
  • idempotent/exception/:IdempotentException。

验证与排障 ​

在 muotai-backend 根目录运行编译校验:

bash
mvn -B -pl :muotai-common-idempotent -am test-compile -DskipTests

运行期验收步骤

  1. 在 expireTime 有效期内使用同一业务键连续提交两次请求,确认首次成功、第二次抛出 IdempotentException 并返回预期提示。
  2. 分别以不同用户或租户发起相同参数的请求,验证键维度隔离是否生效(避免跨用户误拦截)。
  3. 将 delKey = true 后验证方法正常结束与抛异常时键均能正确释放。

重要源码边界(切勿误用于资金/库存强唯一)

  1. 非原子占位写语义:IdempotentAspect 源码调用的是 rMapCache.put(key, value, expireTime, timeUnit) 并通过判断 existingValue != null 拒绝重复请求 —— 重复请求依然会覆盖写入新值并刷新 TTL。它不是“只写入一次(putIfAbsent)”语义,严禁当作支付扣款、库存扣减的唯一性保证;此类核心账务仍须依赖数据库唯一索引、状态机或分布式事务。
  2. 仅限 Servlet HTTP 请求:@Before 直接强转 RequestContextHolder.getRequestAttributes() 为 ServletRequestAttributes,无法用于 MQ 消费者、定时任务或非 Web 线程。
  3. 窗口长度配置:expireTime 必须大于业务方法最大预期耗时;默认仅 1 秒,切忌遗漏配置。

源码入口:muotai-backend/muotai-common/muotai-common-idempotent/src/main/java/com/aroundix/muotai/common/idempotent/aspect/IdempotentAspect.java。相关上下游见公共组件总览。