驗證碼5分鍾有效,60秒不重復發送


1.1application.yml添加連接redis的配置

  # Redis
redis:
  host: localhost
  port: 6379
  password: #密碼(沒有密碼可以不設置)
  database: 0 #連接0庫
  timeout: 0 #連接超時時間(毫秒)
  # 對應 RedisProperties.Jedis 內部類
  jedis:
    pool:
      max-active: 8 # 連接池最大連接數,默認為 8 。使用負數表示沒有限制。
      max-idle: 8 # 默認連接數最小空閑的連接數,默認為 8 。使用負數表示沒有限制。
      min-idle: 0 # 默認連接池最小空閑的連接數,默認為 0 。允許設置 0 和 正數。
      max-wait: -1 # 連接池最大阻塞等待時間,單位:毫秒。默認為 -1 ,表示不限制。

1.2在pet-service新建連接第三方接口redis的RedisService

package cn.pet.service.thirdparty.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisService {

    private static final Logger logger= LoggerFactory.getLogger(RedisService.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //定義方法,向redis存數據
    public void setValue(String key,String value){
        try{
            ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
            vo.set(key,value);
            logger.info("set redis success key={},value={}",key,value);
        }catch (Exception e){
            logger.info("set redis fail e={}",e);
        }
    }

    //定義方法,向redis存數據,設置有效時間
    public void setValue(String key,String value,long time){
        try{
            ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
            //redis中time有效時間,使用秒表示
            vo.set(key,value,time, TimeUnit.SECONDS);
            logger.info("set redis success key={},value={},time={}",key,value,time);
        }catch (Exception e){
            logger.info("set redis fail e={}",e);
        }
    }

    //定義方法,獲取有限時間
    public Long getTime(String key){
        try{
            Long time = stringRedisTemplate.getExpire(key);
            logger.info("有效時間為{},:",time);
            return time;
        }catch (Exception e){
            logger.info("沒有有限時間");
            return null;
        }
    }
}

1.3在pet-service的UmsSmsServiceImpl發送驗證碼成功的地方把驗證碼存入redis,設置有效時間

@Service
@Transactional
public class UmsSmsServiceImpl implements UmsSmsService {
    private static final Logger logger= LoggerFactory.getLogger(AliYunService.class);
    @Autowired
    private AliYunService aliYunService;
    @Autowired
    private RedisService redisService;
    @Override
    public Boolean sendSms(String phone, Integer codeType) {
        //需要生成驗證碼
        String code = MathUtils.random();
        logger.info("手機號碼:{} 短信驗證碼為:{}",phone,code);
        String result = aliYunService.sendSms(phone, code);
        if (result.equals(Constants.Sms.ALI_SMS_RESULT)){
            //短信驗證碼發送成功
            //驗證碼存入redis
            //通過工具shengchengkey
            String key = UmsUtils.generateSmsRedisKey(codeType.toString(), phone);
            redisService.setValue(key,code,Constants.Time.ALI_SMS_EFFECTIVE_TIME);
            return true;
        }
        return false;
    }
}

 

1.4在pet-web的UmsSmsController中添加驗證碼60s不重復發送

package cn.pet.controller;

import cn.pet.constant.Constants;
import cn.pet.result.Result;
import cn.pet.result.ResultEnum;
import cn.pet.result.ResultUtils;
import cn.pet.service.UmsSmsService;
import cn.pet.service.thirdparty.redis.RedisService;
import cn.pet.utils.UmsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/ums/sms")
@RestController
public class UmsSmsController {

    private static final Logger logger= LoggerFactory.getLogger(UmsSmsController.class);
    @Autowired
    private UmsSmsService umsSmsService;
    @Autowired
    private RedisService redisService;
    @PostMapping("/sendSms")
    public Result sendSms(String phone,Integer codeType){
        //判斷手機號
        if (StringUtils.isEmpty(phone) | !UmsUtils.checkPhone(phone)){
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_PHONE_ERROR);
        }

        if (!UmsUtils.checkCodeType(codeType)){
            return ResultUtils.returnResult(ResultEnum.FAIL_UMS_SMS_CODE_TYPE_ERROR);
        }

        //判斷驗證碼在redis中存放夠不夠一分鍾  不夠一分鍾,不能調用sendSms,如果超過一分鍾調用sendSms
        if (checkIsExpire(codeType,phone)){
            logger.info("不能頻繁發送驗證碼");
            return ResultUtils.returnFail("一分鍾之內不能重復發送驗證碼");
        }
        
        //調用service接口
        Boolean aBoolean = umsSmsService.sendSms(phone, codeType);
        if (aBoolean){
            return ResultUtils.returnSuccess();
        }else {
            return ResultUtils.returnFail();
        }
    }

    private Boolean checkIsExpire(Integer codeType,String phone){
        //從redis中獲取有效時間  通過key
        String key = UmsUtils.generateSmsRedisKey(codeType.toString(), phone);
        Long time = redisService.getTime(key);

        if (time> Constants.Time.ALI_SMS_CHECK_TIME){
            //表示驗證碼在redis存放不到一分鍾
            return true;
        }
        return false;

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM