Java后端防止频繁请求、重复提交
在客户端网络慢或者服务器响应慢时,用户有时是会频繁刷新页面或重复提交表单的,这样是会给服务器造成不小的负担的,同时在添加数据时有可能造成不必要的麻烦。所以我们在后端也有必要进行防抖操作。
- 自定义注解
/**
* @author Tzeao
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NoRepeatSubmit {
// 名称,如果不给就是要默认的
String name() default "name";
}
- 使用AOP实现该注解
/**
* @author Tzeao
*/
@Aspect
@Component
public class NoRepeatSubmitAop {
@Autowired
private RedisService redisService;
private Logger logger = LoggerFactory.getLogger(NoRepeatSubmitAop.class);
/**
* 切入点
*/
@Pointcut("@annotation(com.qwt.part_time_admin_api.common.validation.NoRepeatSubmit)")
public void pt() {
}
@Around("pt()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
// 这里是唯一标识,根据情况而定
String key = "1" + "-" + request.getServletPath();
// 如果缓存中有这个url视为重复提交
if (!redisService.hasKey(key)) {
// 通过,执行下一步
Object result = joinPoint.proceed();
// 然后存入redis,并且设置15s倒计时
redisService.setCacheObject(key, 0, 15, TimeUnit.SECONDS);
// 返回结果
return result;
} else {
logger.error("请勿重复提交或者操作过于频繁!");
return Result.fail(400, "请勿重复提交或者操作过于频繁!");
}
}
}
- serice,也可以放在工具包里面,这里我们使用到了Redis来对key和标识码进行存储和倒计时,所以在使用时还需要连接一下Redis
package com.qwt.part_time_admin_api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import