RedisTemplate生成验证码的简单使用

使用redis的一个场景是在redis中存入具有时间限制的验证码
最先使用到的一个方法是.opsForValue()
方法中具体的属性可以参考以下连接中的内容
https://blog.csdn.net/aoxiangzhe/article/details/93164823

接下来遇到的还有.getExpire()这个方法,这个方法可以获取有效时间和指定有效时间

     public long getExpireTime(String key){
    
    
         long time = redisTemplate.getExpire(key);
         return time;
     }
    /**指定秒*/
     public long getExpireTimeType(String key){
    
    
         long time = redisTemplate.getExpire(key,TimeUnit.SECONDS);
         return time;
     }
	/**指定分钟*/
   public long getExpireTimeTypeForMin(String key){
    
    
         long time = redisTemplate.getExpire(key,TimeUnit.MINUTES);
         return time;
     }

下面是使用到的验证码相关的代码

@Api(tags = "验证码")
@RestController
@RequestMapping("/verify")
public class ValidateCodeController {
    
    

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("生成验证码")
    @PostMapping("/generate/{phone}/{hour}")
    public Object generateCode(@PathVariable String phone,Integer hour) {
    
    
        Random random = new SecureRandom();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 10; i++) {
    
    
            int num = random.nextInt(9);
            if (num%2==0) {
    
    
                stringBuilder.append(num);
            } else {
    
    
                stringBuilder.append((char) (65 + random.nextInt(26)));
            }
        }
        String validateCode = stringBuilder.toString();
        ValueOperations forValue = redisTemplate.opsForValue();
        forValue.set(phone, validateCode);
        redisTemplate.expire(phone,hour*60*60,TimeUnit.SECONDS);
        return ResultJson.ok(validateCode);
    }

    @ApiOperation("查看当前验证码")
    @PostMapping("/code/{phone}")
    public Object existCode(@PathVariable String phone){
    
    
        //redis中的验证码
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String code = forValue.get(phone);
        if (code==null||code.equals("")){
    
    
            return ResultJson.ok(ResultCode.NOT_EXIST,"暂未生成下载码或下载码已过期");
        }
        Long second = redisTemplate.getExpire(phone);
        return ResultJson.ok(new VerificationCodeVo(phone,code,second));
    }


    @ApiOperation("验证验证码")
    @PostMapping("/check")
    public Object checkValidateCode(String phone, String code) {
    
    
        if (phone==null || code==null) {
    
    
            return ResultJson.failure(ResultCode.BAD_REQUEST);
        }
        //redis中的验证码
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String validateCodeInRedis = forValue.get(phone);
        //校验
        if (code!=null && validateCodeInRedis!=null && code.equals(validateCodeInRedis)) {
    
    
            return ResultJson.ok("验证成功");
        }
        return ResultJson.failure(ResultCode.UNAUTHORIZED);
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_45121502/article/details/106069438