防重复提交
客户端可以加Confirm确认框,或者Submit后按钮置灰。
本文介绍服务器防重复(基于AOP+Redis)
引入依赖
<!-- 引入AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 引入Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
自定义注解
/**
* 防止重复提交注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {
/**
* 时间周期(秒)
*/
int seconds();
/**
* 最大提交次数
*/
int maxCount();
}
定义注解的AOP代理
@Aspect
@Component
public class NoRepeatSubmitAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RedisTemplate redisTemplate;
/**
* 切入点 关联上注解 @NoRepeatSubmit
*/
@Pointcut("@annotation(noRepeatSubmit)")
public void pointcut(NoRepeatSubmit noRepeatSubmit) {
}
@Around("pointcut(noRepeatSubmit)")
public Object around(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit) throws Throwable {
ServletRequestAttributes att = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = att.getRequest();
int seconds = noRepeatSubmit.seconds();
int maxCount = noRepeatSubmit.maxCount();
// 获取请求 IP
String ip = request.getRemoteAddr();
// Redis key = request:ip
String key = request.getServletPath() + ":" + ip;
// 获取请求次数
Integer count = (Integer) this.redisTemplate.opsForValue().get(key);
if (count == null) {
count = 0;
}
this.logger.info("key={}, count={}, seconds={}, maxCount={}", key, count, seconds, maxCount);
if(count == 0) {
count++;
this.redisTemplate.opsForValue().set(key, count, seconds, TimeUnit.SECONDS);
return joinPoint.proceed();
} else if (count.intValue() < maxCount) {
count++;
this.redisTemplate.opsForValue().set(key, count, 0);
return joinPoint.proceed();
}
return "访问失败";
}
}
使用注解
@NoRepeatSubmit(seconds = 5, maxCount = 1)
@RequestMapping(value = "login", method = RequestMethod.GET)
public String login(@RequestParam("userName") String userName, String phoneNo) {
UserVO userVO = new UserVO();
userVO.setUserName(userName);
userVO.setPhoneNo(phoneNo);
LoginEvent userEvent = new LoginEvent(userVO);
publisher.publishEvent(userEvent);
return userName + " login success!";
}
测试结果
5秒内只能访问一次。