Redis——模拟手机验证码发送

316 阅读2分钟

使用redis模拟手机验证码发送,规定一个手机号一天只能请求三次验证码,且每次请求的验证码只有两分钟就会过期

1、首先写一个函数随机产生六位验证码,使用random函数

`

public static String getCode(){

    String code="";
    Random random = new Random();
    //随机函数生成验证码
    for (int i = 0; i < 6; i++) {
        code+= random.nextInt(10);
    }
    return code;
}`

2、写一个函数判断一个手机号一天验证码发送次数,流程如下:

①使用jedis连接redis,第一个参数为linux虚拟地址,第二个参数为redis默认端口号

②生成存储手机号发送次数,验证码对应的key

③判断该手机号一天发送验证码的次数,为空表明手机号未请求过,则将手机号次数存储进入,bi并设置过期时间为1天,若小于三次则自增

④存储验证码进redis,并设置过期时间为2分钟

`public static Boolean Phone(String phone){
    //连接linux中的redis
    Jedis jedis = new Jedis("192.168.12.188",6379);
    //生成手机存储的key
    String phoneKey="Phone"+phone+"p";
    //生成存储验证码的key
    String codeKey="Code"+phone+"c";
    //获取key为phoneKey的值
    String key = jedis.get(phoneKey);
    //判断redis中phoneKey值是否为空
    if (key==null){
        //为空存储phoneKey,并设置过期时间为1天,值为1,代表发送过一次
        jedis.setex(phoneKey,24*60*60,"1");
    }
    //若不为空,且发送次数小于3,phoneKey++
    else if (Integer.parseInt(key)<=2){
        jedis.incr(phoneKey);
    }
    //若发送超过三次,提示不能发送
    else {
        System.out.println("今天发送次数已经超过三次,不能再获取验证码");
        jedis.close();
        return false;
    }
    //获取验证码
    String code=getCode();
    //存储验证码
    jedis.setex(codeKey,120,code);
    jedis.close();
    return true;
}`

3、判断验证码是否正确

①通过手机号拼接字符串,获取验证码的key值

②验证验证码是否正确

public static Integer Code(String code,String phone){
    //连接jedis
    Jedis jedis = new Jedis("192.168.23.129",6379);
    String codekey="Code"+phone+"c";
    String s = jedis.get(codekey);
    //判断验证码是否正确
    if (code.equals(s)){
        System.out.println("验证码正确");
        return 1;
    }else {
        System.out.println("验证码错误,请重新请求");
        return 0;
    }
}

4、启动linux中redis服务端,找到redis.conf,启动执行下面命令即可启动

redis-server /opt/redis-6.2.1/redis.conf

5、执行函数

①输入手机号,并确认是否发送验证码

②调用判断手机号发送验证码次数函数,判断是否三次已经发完,若发完,直接退出

③输入验证码,调用验证验证码函数,若正确,直接退出程序

④若输入验证码失败,确认是否继续发送验证码

public static void main(String[] args) {
    //创建一个手机号
    String phone="";
    String tip="";
    Scanner scanner = new Scanner(System.in);
    System.out.print("请输入手机号:");
    phone=scanner.nextLine();
    System.out.print("是否获取验证码:(y/n)");
    tip=scanner.nextLine();
    if (tip.equals("y")){
        while (tip.equals("y")){
            //打印验证码到控制台
            Boolean p=Phone(phone);
            if (!p){
                //发送超过三次,退出while
                break;
            }
            System.out.println(getCode());
            System.out.print("请输入验证码:");
            String code=scanner.nextLine();
            if (Code(code,phone).equals(1)){
                System.out.println("验证超过");
                break;
            }
            System.out.print("是否重新获取验证码:(y/n)");
            tip=scanner.nextLine();
        }
    }

}

运行结果如下

微信截图_20220303115109.png