验证码防刷

原理

引入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;
   }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值