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

Spring boot 注解实现幂等性

1. 添加 Spring AOP 依赖

在 pom.xml 中添加如下依赖:

<dependencies><!-- Spring AOP dependency --><dependency><groupIdorg.springframework.boot</groupId><artifactIdspring-boot-starter-aop</artifactId></dependency>
</dependencies>

2. 创建自定义幂等性注解

创建一个新的 Java 注解类,通过 @interface 关键字来定义,并可以添加元注解以及属性。

/**
* 《像乌鸦一样思考》让孩子学会观察和独立思考!
* https://www.sanzhiwa.top/6718.html
*/
@Retention(RetentionPolicy.RUNTIME) // 程序运行时有效
@Target(ElementType.METHOD) // 方法注解
public @interface Idempotent {/*** 请求标识符的参数名称,默认为"requestId"*/String requestId() default "requestId";/*** 幂等有效时长(单位:秒)*/int expireTime() default 60;
}

3. 创建拦截器

/**
* 清华附小1-6年级趣味英语动画
* https://www.sanzhiwa.top/6711.html
*/
@Component
public class IdempotentInterceptor extends HandlerInterceptorAdapter {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Method method = ((HandlerMethod) handler).getMethod();Idempotent idempotent = method.getAnnotation(Idempotent.class);if (idempotent != null) {// 获取请求中的唯一标识符String requestId = obtainRequestId(request, idempotent.requestId());// 判断该请求是否已经处理过if (redisTemplate.opsForValue().get(idempotentKey(requestId)) != null) {// 已经处理过,返回幂等响应response.getWriter().write("重复请求");return false;} else {// 将请求标识符存入Redis,并设置过期时间redisTemplate.opsForValue().set(idempotentKey(requestId), "processed", idempotent.expireTime(), TimeUnit.SECONDS);return true; // 继续执行业务逻辑}}return super.preHandle(request, response, handler);}private String idempotentKey(String requestId) {return "idempotent:" + requestId;}private String obtainRequestId(HttpServletRequest request, String paramName) {// 实现从请求中获取唯一标识符的方法return request.getParameter(paramName);}
}

4. 配置拦截器

在 Spring Boot 配置文件类中,添加拦截器配置:

/**
* 儿童新概念英语
* https://www.sanzhiwa.top/6696.html
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate IdempotentInterceptor idempotentInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(idempotentInterceptor).addPathPatterns("/**"); // 拦截所有接口}
}

5.使用自定义注解

最后,在需要进行幂等控制的 Controller 方法上使用 @Idempotent 注解:

/**
*
* 微观小世界】奇趣探险,启程进入神秘的微观世界!
* https://www.sanzhiwa.top/6704.html
*/
@RestController
public class TestController {@PostMapping("/order")@Idempotent(requestId = "orderId") // 假设orderId是从客户端传来的唯一标识订单请求的参数public String placeOrder(@RequestParam("orderId") String orderId, ...) {// 业务处理逻辑}
}

这样,当有相同的请求 ID 在指定的有效期内再次发起请求时,会被拦截器识别并阻止其重复执行业务逻辑

http://www.lryc.cn/news/372595.html

相关文章:

  • NVIDIA Jetson AI边缘计算盒子
  • React核心概念、主要特点及组件的生命周期
  • Java基础面试重点-1
  • 18. 四数之和 - 力扣
  • [vue2]深入理解路由
  • 搜维尔科技:SenseGlove为什么不同的手套尺寸对触觉技术至关重要
  • java算法:选择排序
  • helm升级部署时出现升级挂起状态处理
  • 16、架构-可观测性-事件日志详细解析
  • Java数据结构与算法(买卖股票的最佳时机二贪心算法)
  • t265 坑
  • 【LLM之RAG】Adaptive-RAG论文阅读笔记
  • 介绍react
  • 网络爬虫概述
  • 取证工作: SysTools SQL Log Analyzer, 完整的 SQL Server 日志取证分析
  • 蓝牙耳机怎么连接电脑?轻松实现无线连接
  • 4.音视频 AAC SSAASS
  • 每日5题Day24 - LeetCode 116 - 120
  • 在笔记本电脑上使用 LLMs 的 5 种方法
  • Linux内存从0到1学习笔记(8.15 MMU/IOMMU/SMMU概览)
  • Intellij IDEA中怎么配置Maven?
  • 操作系统-内存管理
  • C++中的解释器模式
  • 用 C 语言实现求补码的运算
  • python下载文件
  • JMU 数科 数据库与数据仓库期末总结(1)
  • 前端问题整理
  • 【实践功能记录6】表格列悬浮展示tooltip信息
  • AI论文速读 | 2024[SIGIR]基于大语言模型的下一个兴趣点推荐
  • Rust 实战丨通过实现 json! 掌握声明宏