顺手写的一个防重复提交
注解定义
package com.xf.common; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Administrator 顺手写的一个防重复提交注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ReSubmit { // 执行时间 int delaySeconds() default 50; }
拦截器实现
package com.xf.config; import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import com.xf.common.BizException; import com.xf.common.ErrorCode; import com.xf.common.ReSubmit; import cn.hutool.core.lang.Console; import cn.hutool.extra.spring.SpringUtil; /** * @author ckw * @version 1.0 * @date 2020/6/11 10:11 * @description: 拦截重复提交数据 */ @Component public class ReSubmitInterceptor implements HandlerInterceptor { // @Autowired RedisTemplate redisTemplate; @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // redisTemplate.delete(getKey(request)); HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) return true; HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); // 拿到方法上面的自定义注解 ReSubmit annotation = method.getAnnotation(ReSubmit.class); // 如果不等于null说明该方法要进行幂等 if (null != annotation) { redisTemplate = SpringUtil.getBean(RedisTemplate.class); redisTemplate.opsForValue().set("aa", "aa"); boolean succ = redisTemplate.opsForValue().setIfAbsent(getKey(request), 0, annotation.delaySeconds(), TimeUnit.SECONDS); if (!succ) throw new BizException(ErrorCode.ReSubmit); } return true; } String getKey(HttpServletRequest request) { // String token = request.getHeader("token"); String token = ""; String url = request.getServletPath(); Console.log(token + url); return token + url; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人