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

Redis实现简单的验证码功能(简单)

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

Redis实现简单的验证码功能(简单)

Redis的简单验证码

原理代码实现

此次代码仅适合初学者进行学习Redis,能够初步的掌握Redis在ideal中的基本操作,代码简单易懂

原理
    生成随机的验证码。可以通过java的Random随机函数进行产生建立函数生成key ,设置Redis设置过期时间,并将key值与验证码写入到Redis中读取生成的验证进行校验
代码实现

创建maven项目 配置pom.xml



    4.0.0

    org.example
    redisTest
    1.0-SNAPSHOT

    
        redis.clients
        jedis
        3.2.0
    
    
        junit
        junit
        4.12
        compile
    


    生成随机的六位数验证码
 //生成随机的六位数
    public  static  String getCode(){
        Random random = new Random();
        String code="";
        for(int i=0;i<6;i++){
            //生成10以内的10位数随机整数
            int rand = random.nextInt(10);
           //拼接随机数
            code+=rand;
        }
        return  code ;
    }
    将验证码写入到Redis中,并设定过期时间(2分钟),每天只能生成三次验证码
 public static void verifyCode(String Phone){
        Jedis jedis = new Jedis("niit02", 7001);
        String  CountKey="verify"+Phone+":count";
        String  CodeKey="verify"+Phone+":code";
        String count = jedis.get(CodeKey);
        if(count==null){
            jedis.setex(CountKey,24*60*60,"1");

        }else if(Integer.parseInt(count)<=2){
            jedis.incr(CountKey);
        }else if (Integer.parseInt(count)>2) {
            System.out.println("三次机会已经用完");
            jedis.close();
        }
        String code = getCode();
        jedis.setex(CodeKey,120,code);
        jedis.close();
    }
    验证手机号和验证码
 ///验证,手机号与验证码
    public static void getRdisCode (String Phone,String Code){
        Jedis jedis = new Jedis("niit02", 7001);
        String  CodeKey="verify"+Phone+":code";
        String redisCode = jedis.get(CodeKey);
        System.out.println(redisCode);
        if(redisCode.equals(Code)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
       jedis.close();
    }
    主函数调用
 public static void main(String[] args) {
//verifyCode("15182021426");

getRdisCode("15182021426","756430");
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/776185.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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