當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot+Redis防止接口重复提交
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot+Redis防止接口重复提交
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
在項目的使用使用過程中,經常會出現某些操作在短時間內頻繁提交。例如:用戶鼠標點擊過快而重復保存,從而創建了2筆一模一樣的單據。針對類似情況,我們就可以全局地控制接口不允許重復提交。
實現思路
- 創建攔截器 Interceptor,攔截所有API請求
- 將用戶唯一標識(token或者jsessionid)+接口地址進行拼接,作為后續步驟的 redis-key
- 判斷Redis是否存在該key值,存在說明重復提交,不存在就存入Redis,過期時間1秒
代碼示例
創建攔截器 RepeatSubmitInterceptor
@Component public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {@Autowiredprivate StringRedisTemplate stringRedisTemplate;//防重時間間隔(秒)private final int duration = 1;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {if (request.getDispatcherType() == DispatcherType.ERROR){return true;}String token = request.getHeader("token");String lockKey = "RepeatSubmit:" + token + ":" + request.getServletPath();Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "", duration, TimeUnit.SECONDS);if (!result){throw new Exception("請勿重復提交");}return true;} }注入攔截器
@Configuration public class MvcConfig implements WebMvcConfigurer {@Autowiredprivate RepeatSubmitInterceptor repeatSubmitInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(repeatSubmitInterceptor);} }測試
建個 controller 并創建個簡單的測試接口,打開 postman 快速點擊2次請求,結果如下:
總結
這邊只是提供一種簡單的方案,還可以有其他擴展,例如:
- 增加參數的校驗,只做相同參數的重復判定,參數不同可以重復提交
- 增加AOP自定義注解,只有注解標識的接口才會重復判定
- 使用Session替代Redis進行存儲和校驗(不適用于tomcat集群)
總結
以上是生活随笔為你收集整理的SpringBoot+Redis防止接口重复提交的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot 序列化与反序列化日
- 下一篇: Redis5.0.8集群搭建与说明