项目方案:Java 批量给接口添加防重复点击功能

简介

在开发Web应用中,经常会遇到用户频繁点击按钮或发送重复请求的情况,为了避免这种情况发生,我们需要在接口层面添加防重复点击的功能。本文将介绍如何使用Java来批量为接口添加防重复点击功能。

方案

步骤一:定义注解

首先,我们需要定义一个注解来标识哪些接口需要添加防重复点击功能。我们可以定义一个@PreventDuplicateClick注解来标记需要添加该功能的接口。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PreventDuplicateClick {

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
步骤二:添加拦截器

接下来,我们需要编写一个拦截器来处理添加了@PreventDuplicateClick注解的接口。在拦截器中,我们可以使用Redis等缓存工具来记录用户的点击状态,并在一定时间内拦截重复点击的请求。

public class PreventDuplicateClickInterceptor implements HandlerInterceptor {

    private static final String DUPLICATE_CLICK_PREFIX = "duplicate_click_";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Method handlerMethod = ((HandlerMethod) handler).getMethod();
        
        if (handlerMethod.isAnnotationPresent(PreventDuplicateClick.class)) {
            String key = DUPLICATE_CLICK_PREFIX + request.getRequestURI() + "_" + request.getSession().getId();
            if (redisTemplate.opsForValue().setIfAbsent(key, "1")) {
                redisTemplate.expire(key, 5, TimeUnit.SECONDS);
                return true;
            } else {
                response.getWriter().write("请勿频繁点击");
                return false;
            }
        }
        
        return true;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
步骤三:配置拦截器

最后,我们需要在Spring Boot中进行拦截器的配置,将PreventDuplicateClickInterceptor添加到拦截器链中。

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private PreventDuplicateClickInterceptor preventDuplicateClickInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(preventDuplicateClickInterceptor).addPathPatterns("/**");
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

流程图

flowchart TD
    A[用户发送请求] --> B{是否添加@PreventDuplicateClick注解}
    B -- 是 --> C[生成缓存key并判断是否存在]
    C -- 存在 --> D[拦截请求,返回重复点击提示]
    C -- 不存在 --> E[放行请求]
    B -- 否 --> E

结论

通过以上步骤,我们可以批量为接口添加防重复点击功能,避免用户频繁点击按钮或发送重复请求的情况。这种方法不仅简单高效,而且可以有效提升用户体验和系统性能。希望本文能够帮助到你在开发中遇到类似问题时快速解决。