栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot整合redis模拟手机验证码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合redis模拟手机验证码

1:前提

 

        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            org.apache.commons
            commons-pool2
            2.6.0
        
        
            redis.clients
            jedis
            3.3.0
        

 

 看看是否连接成功!

        Jedis jedis=new Jedis("你的host",6379);
        jedis.auth("密码,如果没有就不用写");
        String value= jedis.ping();
        System.out.println(value);

说明连接成功了!

如果连接失败,可以看看端口是否放行等,网上搜一搜答案很多,这里不赘述!

 既然模拟手机验证码 ,可以直接随机数生成一个六位数的验证码。

        Random random= new Random();
        String code="";
        for(int i=0;i<6;i++){
            int rand=random.nextInt(10);
            code+=rand;
        }
        return code;

只允许发送三次

        //连接
        Jedis jedis= new Jedis("你的host",6379);
        jedis.auth("密码");

        //发送次数
        String countKey="VeriFycode:"+phone+"count";
        String codeKey = "VeriFycode:"+phone+"code";
        //3次
        String count = jedis.get(countKey);
        if(count ==null){
            jedis.setex(countKey,24*60*60,"1");//setex 设置生存实践
        }
        else if(Integer.parseInt(count)<=2){
            jedis.incr(countKey);//发送一次让cout加一
        }
        else{
            System.out.println("最多只能发送3次!");
            jedis.close();
        }

        //验证码放到redis
        String vcode=getCode();
        jedis.setex(codeKey,120,vcode);
        jedis.close();

然后是验证

        //连接
        Jedis jedis= new Jedis("你的host",6379);
        jedis.auth("密码");

        //验证
        String codeKey="VeriFycode--"+phone+"--code";
        String redisCode=jedis.get(codeKey);
        if(redisCode.equals(code)){
            System.out.println("验证码正确!");
        }else{
            System.out.println("验证码错误!");
        }
        jedis.close();

我们来验证一下:

 

 成功!

 

 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353309.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号