当前位置:   article > 正文

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

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

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

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

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

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

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface NoRepeatRequest {
  4. }

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

  1. @Component
  2. public class NoRepeatRequestInterceptor implements HandlerInterceptor {
  3. private Map<String, Object> requestMap = new ConcurrentHashMap<>();
  4. @Override
  5. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  6. // 获取请求的URL和方法名
  7. String url = request.getRequestURL().toString();
  8. String method = request.getMethod();
  9. // 生成请求的唯一标识
  10. String key = url + "_" + method;
  11. // 如果容器中已存在该请求,则表示是重复请求
  12. if (requestMap.containsKey(key)) {
  13. response.getWriter().write("Duplicate request");
  14. return false;
  15. }
  16. // 将请求添加到容器中
  17. requestMap.put(key, new Object());
  18. return true;
  19. }
  20. @Override
  21. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  22. // 请求处理完毕后,从容器中移除该请求
  23. String url = request.getRequestURL().toString();
  24. String method = request.getMethod();
  25. String key = url + "_" + method;
  26. requestMap.remove(key);
  27. }
  28. }

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

  1. @Configuration
  2. public class WebConfig implements WebMvcConfigurer {
  3. @Autowired
  4. private NoRepeatRequestInterceptor noRepeatRequestInterceptor;
  5. @Override
  6. public void addInterceptors(InterceptorRegistry registry) {
  7. registry.addInterceptor(noRepeatRequestInterceptor)
  8. .addPathPatterns("/**") // 可以根据具体的URL进行配置
  9. .excludePathPatterns("/error"); // 排除错误页面的拦截
  10. }
  11. }

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

  1. @Controller
  2. public class TestController {
  3. @NoRepeatRequest
  4. @RequestMapping("/test")
  5. @ResponseBody
  6. public String test() {
  7. // 处理业务逻辑
  8. return "success";
  9. }
  10. }

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/234245
推荐阅读
相关标签
  

闽ICP备14008679号