Redis整合SpringBoot项目----dome手机验证码

前几步全部看我上文章

https://blog.csdn.net/weixin_50235904/article/details/122240255?spm=1001.2014.3001.5501

编写一个Controller

关于手机验证码

/**
 * @Date 2021/12/31
 * @Author Acer
 */
@RestController
@RequestMapping("/phonecode")
public class PhoneController {
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 生成一个验证码
     * 根据一个手机号或得一个六位数的随机数
     * 存入redis缓存,20秒
     */
    @RequestMapping("/haveCode")
    public Object haveCode(String phone) {
    if(redisTemplate.opsForValue().get(phone)!=null){
            return "已经发送验证码,20秒之后再试!!";
        }
        int[] number = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int is = random.nextInt(10);//10秒换一个数
            stringBuilder.append(number[is]);//存到stringBuilder中
        }
        redisTemplate.opsForValue().set(phone, stringBuilder, 20, TimeUnit.SECONDS);//存入redis中20秒
        return "验证码为:" + stringBuilder;
    }

    /**
     * 验证验证码
     * 传入手机号和验证码
     */
    @RequestMapping("yz")
    public Object yz(String phone, String code) {
        if (redisTemplate.hasKey(phone) == false) {
            return "手机号没有验证码验证码过期";
        }
        if (code.equals(redisTemplate.opsForValue().get(phone))) {
            return "验证码正确";
        }
        return "验证码错误";
    }
}

通过访问接口
http://localhost:8081/phonecode/haveCode?phone=“设置手机号”
在20秒之内访问接口
http://localhost:8081/phonecode/yz?phone=“设置手机号”&code=“获取的验证码”

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值