redis操作-RedisTemplate保存和获取数据

发布时间 2023-05-28 19:32:28作者: TestRookie
public Result sendCode(@PathVariable String phone){
        //从redis中获取验证码,如果获取到,返回ok
        //redis的key为手机号 value为验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //从redis中获取不到验证码,生成验证码
        code = RandomUtil.getSixBitRandom();
        boolean isSend = msmService.send(phone,code);
        //生成验证码,保存到redis中,设置有效时间
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);//3分钟内有效
            return Result.ok();
        }else {
            return Result.fail("发送短信失败");
        }
    }