原理

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

Logo

网易易盾是国内领先的数字内容风控服务商,依托网易二十余年的先进技术和一线实践经验沉淀,为客户提供专业可靠的安全服务,涵盖内容安全、业务安全、应用安全、安全专家服务四大领域,全方位保障客户业务合规、稳健和安全运营。

更多推荐