1.功能实现:

(1)输入手机号,点击生成随机6位数字码,2分钟有效
(2)输入验证码,点击认证,返回成功或失败
(3)每个手机号只能输入三次

2.函数介绍

public static String getCode()   //用于实现验证码的随机生成`public static void verifyCode(String phone)//每个手机只能每天输入三次,验证码2分钟有效public static void getRedidCode(String phone,String code)//验证 客户端输入 与验证码

3.实现

初始库状态
在这里插入图片描述
1.验证码生成
在这里插入图片描述
库状态:
在这里插入图片描述
验证码已存入
在这里插入图片描述
此时只调用验证功能
在这里插入图片描述
代码实现

package Redis_phone;
import java.io.*;

import java.util.*;
import com.sun.java_cup.internal.runtime.Scanner;
import redis.clients.jedis.Jedis;

import java.util.Random;

//实现手机验证
public class phone {
    /*
    (1)输入手机号,点击生成随机6位数字码,2分钟有效
    (2)输入验证码,点击认证,返回成功或失败
    (3)每个手机号只能输入三次
    * */
    public static void main(String[] args) {
        //String code = getCode();
        //System.out.println(code);
        //verifyCode("18560266808");
        getRedidCode("18560266808","064783");
    }

    //1.随机生成6位验证码
    public static String getCode(){
        Random random = new Random();
        String code ="";
        for(int i=0; i<6 ;i++){
            int nextInt = random.nextInt(10);
            code += nextInt;
        }
        return code;
    }
    //2.每个手机只能每天输入三次,验证码2分钟有效
    public static void verifyCode(String phone){
        //1.创建对象
        Jedis jedis = new Jedis("192.168.58.152", 6379);
        //2.拼接key:手机发送次数的key;验证码的key
        String countKey = "VerifyCode"+phone+":count";
        String codeKey = "VerifyCode"+phone+":code";
        //3.判断每个手机验证码发送的次数(不能超过3次)
        String count = jedis.get(countKey);
        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(phone+":发送次数已经超过三次!!");
            jedis.close();
        }

        //4.将验证码存到Redis
        String Vcode = getCode();
        System.out.println("验证码:"+Vcode);
        jedis.setex(codeKey,120,Vcode);
        jedis.close();


    }
    //验证 客户端输入 与验证码
    public static void getRedidCode(String phone,String code){

        String codeKey = "VerifyCode"+phone+":code";
        //1.创建对象
        Jedis jedis = new Jedis("192.168.58.152", 6379);

        String redis_code = jedis.get(codeKey);  //验证码
      //判断验证码是否正确
        if(redis_code.equals(code))
        {
            System.out.println("成功");
        }else{
            System.out.println("失败");
        }
        jedis.close();


    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐