SpringBoot接口防抖(防重复提交)
在Spring Boot中实现接口防抖,可以通过自定义注解和拦截器来实现。以下是一个简单的示例:
- 自定义注解
AntiDingding
:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AntiDingding {
long timeout() default 5000;
}
- 创建拦截器
AntiDingdingInterceptor
:
@Component
public class AntiDingdingInterceptor implements HandlerInterceptor {
private final Map<String, Long> cache = new ConcurrentHashMap<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
AntiDingding antiDingding = method.getAnnotation(AntiDingding.class);
if (antiDingding != null) {
String key = getKey(request);
Long lastTime = cache.get(key);
long currentTime = System.currentTimeMillis();
if (lastTime != null && currentTime - lastTime < antiDingding.timeout()) {
// 如果在指定的时间内重复提交,则返回false,不执行方法
return false;
}
cache.put(key, currentTime);
}
}
return true;
}
private String getKey(HttpServletRequest request) {
// 根据实际情况生成唯一的key,例如可以使用用户ID、请求的URL等
return request.getRequestURI();
}
}
- 注册拦截器
AntiDingdingInterceptor
:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private AntiDingdingInterceptor antiDingdingInterceptor;
@Override
public void addInterceptors(InterceptorRegistry
评论已关闭