spring boot 实现一个 禁止重复请求

在Spring Boot中,实现禁止重复请求可以通过以下步骤:

1.添加依赖 首先,需要添加Spring Boot的Web依赖,在pom.xml文件中添加以下依赖:

xml 复制代码
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.创建自定义注解 创建一个自定义的注解,用于标注需要进行重复请求限制的方法。可以通过@Retention(RetentionPolicy.RUNTIME)注解来指定注解的保留策略。

java 复制代码
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NoRepeatRequest {
}

3.编写拦截器 创建一个拦截器,用于拦截标有@NoRepeatRequest注解的方法。在拦截器中可以使用一个容器来存储已处理的请求,比如使用ConcurrentHashMap。

java 复制代码
@Component
public class NoRepeatRequestInterceptor implements HandlerInterceptor {

   private Map<String, Object> requestMap = new ConcurrentHashMap<>();

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       // 获取请求的URL和方法名
       String url = request.getRequestURL().toString();
       String method = request.getMethod();

       // 生成请求的唯一标识
       String key = url + "_" + method;

       // 如果容器中已存在该请求,则表示是重复请求
       if (requestMap.containsKey(key)) {
           response.getWriter().write("Duplicate request");
           return false;
       }

       // 将请求添加到容器中
       requestMap.put(key, new Object());
       return true;
   }

   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       // 请求处理完毕后,从容器中移除该请求
       String url = request.getRequestURL().toString();
       String method = request.getMethod();
       String key = url + "_" + method;
       requestMap.remove(key);
   }
}

4.注册拦截器 在配置类中注册拦截器,并将其应用于需要进行重复请求限制的方法。

java 复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {

   @Autowired
   private NoRepeatRequestInterceptor noRepeatRequestInterceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(noRepeatRequestInterceptor)
               .addPathPatterns("/**")  // 可以根据具体的URL进行配置
               .excludePathPatterns("/error");  // 排除错误页面的拦截
   }
}

现在,只需要在需要进行重复请求限制的方法上添加@NoRepeatRequest注解即可。

java 复制代码
@Controller
public class TestController {

   @NoRepeatRequest
   @RequestMapping("/test")
   @ResponseBody
   public String test() {
       // 处理业务逻辑
       return "success";
   }
}

这样,当重复请求该方法时,会返回"Duplicate request",避免重复执行相同的操作。

以上就是使用Spring Boot实现禁止重复请求的方法。通过自定义注解、拦截器和容器,可以实现对重复请求的限制。

相关推荐
IT_陈寒18 小时前
React useEffect里面写异步,我的状态怎么老丢?
前端·人工智能·后端
程序员爱钓鱼19 小时前
第一个 Rust 程序 Hello World
后端·rust
卷福同学1 天前
不用服务器,不用配环境,我10分钟上线了一个AI Agent
人工智能·后端·算法
小明bishe181 天前
计算机毕业设计之基于JAVA的植物科普网站
java·spring boot·spring·架构·课程设计
GetcharZp1 天前
只需 10 分钟,轻松实现异地组网!Netmaker 保姆级部署教程来了
后端
前端兰博1 天前
03-Spring Boot
后端
前端兰博1 天前
01-Java开发基础语言
后端
前端兰博1 天前
02-Servlet、JDBC、Maven、Mybatis
后端
咖啡八杯1 天前
GoF设计模式——模板方法模式
java·后端·spring·设计模式
码事漫谈1 天前
Loop 正在排斥人为操作
后端