原理
引入redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
代码实现
/**
* 验证码防刷
* @return
*/
@GetMapping("/sendCode")
public Integer sendCodes(String account,HttpServletRequest request){
if (account == null){
throw new BizException(303,"请输入手机号或者验证码");
}
String key1 = "sms.code"+account;
// String ip = request.getHeader("XPI");
// String key3="sms.code"+ip;
// 防止同一个ip地址,每天多次刷
// Long count = valueOperations2.increment(key3);
// if (count ==1L){
// redisTemplate.expire(key3,1,TimeUnit.DAYS);
// }
// if (count >10){
// throw new RuntimeException("一个ip地址,每天最多发送10次");
// }
//防止一分钟内多次发送验证码
if (redisTemplate.hasKey(key1)){
throw new BizException(300,"请勿多次点击");
}
//防止一天内多刷,最多5次
String key2=StrUtil.format("sms.code.{}.{}",account,DateUtil.now());
Long count = valueOperations2.increment(key2);
if (count ==1L){
redisTemplate.expire(key2,1,TimeUnit.DAYS);
}
if (count > 5){
throw new BizException(301,"一天最多发送5次");
}
//判断类型
boolean b = Validator.isEmail(account);
if (b){
sendCode(account);
}else {
sendTelCode(account);
}
valueOperations.set(key1,DateUtil.now(),60,TimeUnit.SECONDS);
valueOperations2.increment(key2);
// valueOperations2.increment(key3);
return 0;
}