在idea中用redis实现简单的发送验证码的功能

 

         启动redis

redis-server /opt/redis-5.0.4/redis.conf
redis-cli

发送验证码案例

        1.用random生成一个6位数的随机验证码

    //生成验证码
    public static String getCode(){
        Random random = new Random();
        String code="";
        for (int i = 0; i < 6; i++) {
            int i1 = random.nextInt(10);
            code += i1;
        }
        return code;
    }

        2.向redis中存储验证码,并限制发送的次数

  //发送验证码
    public static void verifyCode(String phone){
        Jedis jedis = JedisPoolUtil.getJedis();
        //验证码的key
        String codeKey = "verifyCode"+phone+"code";
        //记录验证码的次数 key
        String countKey ="verifyCode"+phone+"count";
 
 
 
        String count = jedis.get(countKey);
 
        if(count==null){
            jedis.setex(countKey,60L,"1");
        }else if(Integer.parseInt(count)<=2){
            jedis.incr(countKey);
        }else{
            System.out.println("超过发送的次数");
            jedis.close();
            return;
        }
 
 
        String code = getCode();
 
        System.out.println("验证码:"+code);
        jedis.setex(codeKey,60L,code);
        jedis.close();
 
    }

        3.验证用户发送的验证码是否匹配

    public static void getRedisCode(String phone,String code){
        Jedis jedis = JedisPoolUtil.getJedis();

        String codeKey = "verifyCode"+phone+"code";
        String vcode =jedis.get(codeKey);
 
        if(vcode==null){
            System.out.println("验证码过期了");
        }else  if(vcode.equalsIgnoreCase(code)){
            System.out.println("验证成功");
        }else {
            System.out.println("验证失败");
        }
        jedis.close();
    }

        4.编写main方法进行测试

    public static void main(String[] args) {
        //模拟验证码的发送:phone
        verifyCode("18635183513");
 
        //验证用户输入的验证码和redis的验证码做比较
        getRedisCode("18635183513","722225");
    }

        要先发送验证码到redis数据库

         然后再进行测试

        因为我们设置了1分钟的过期时间,等1分钟后就会看到验证码失效

         如果验证码没有失效但验证码错误会提示验证不通过

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值