Redis(二) -- 练习

模拟手机验证码

需求:使用redis模拟手机验证码发送,验证码有效期60s,验证验证码输入不能超过3次,超过3次今天就没机会了

//验证手机号
/**
 * 判断字符串是否符合手机号码格式
 * 移动号段:   134 135 136 137 138 139 147 148 150 151 152 157 158 159  165 172 178 182 183 184 187 188 198
 * 联通号段:   130 131 132 145 146 155 156 166 170 171 175 176 185 186
 * 电信号段:   133 149 153 170 173 174 177 180 181 189  191  199
 * 虚拟运营商: 170
 */
// "[1]"代表下一位为数字可以是几,"[0-9]"代表可以为0-9中的一个,"[5,7,9]"表示可以是5,7,9中的任意一位,[^4]表示除4以外的任何一个,\\d{8}"代表后面是可以是0~9的数字,有8位。
String regex = "^((13[0-9])|(14[5,6,7,9])|(15[^4])|(16[5,6])|(17[0-9])|(18[0-9])|(19[1,8,9]))\\d{8}$";
public class PhoneDemo {
    public static void main(String[] args) throws InterruptedException {
        JedisPool pool = new JedisPool("linux01", 6379);
        Jedis jedis = pool.getResource();


        Scanner sc = new Scanner(System.in);
        System.out.print("请输入您的手机号:");
        String phoneNum = sc.nextLine();

        String regex="^((13[0-9])|(14[5,6,7,9])|(15[^4])|(16[5,6])|(17[0-9])|(18[0-9])|(19[1,8,9]))\\d{8}$";
        boolean matches = phoneNum.matches(regex);
        if (matches){
            //造验证码
            String code = getCode();

            //将验证码写到redis中  key:手机号  value:验证码
            jedis.setex(phoneNum,6,code);

            int count = 1;

            while (count <=3){
                //输入验证码
		System.out.print("请输入验证码:");
                String yourCode = sc.next();
                if(yourCode.equals(jedis.get(phoneNum))){
                    System.out.println("登录成功!!!");
                    //成功了就退出去
                    break;
                }else{
                    if (count == 3){
                        System.out.println("3次机会已经用完了!");
                    }else{
                        System.out.println("输入错误,请重新输入:");
                    }
                    count++;
                }
            }
        }else {
            System.out.println("手机号不正确");
        }
    }

    public static String getCode(){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int num = new Random().nextInt(10);
            sb.append(num);
        }
        return sb.toString();
    }
}
posted @ 2023-06-03 23:42  _泡泡  阅读(27)  评论(0编辑  收藏  举报