Jedis——手机验证码操作

发布时间 2023-06-02 19:09:09作者: 佛系粥米

要求

1、输入手机号,点击发送后随机生成6为数字码,2分钟有效

Random、验证码存进Redis并设置过期时间120秒

2、输入验证码,点击验证,返回成功或失败

从Redis中获取验证码比对输入验证码

3、每个手机号每天只能输入3次

incr每次发送加1,大于2之后,提醒不能发送

package com.atguigu.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

public class PhoneCode {

    //生成6位数验证码
    public static String getCode(){
        String res = "";
        Random random = new Random();
        for(int i=0; i<6; i++){
            int rand = random.nextInt(10);
            res += rand;
        }
        return  res;
    }

    //2、每个手机每天只能发送三次,验证码放到Redis中,设置过期时间
    public static void verifyCode(String phone){
        //连接redis
        Jedis jedis = new Jedis("192.168.189.128", 6379);
        //手机发送次数key
        String countKey = "Verifycode" + phone + "count";
        //验证码key
        String codeKey = "Verifycode" + phone + "code";

        String count = jedis.get(countKey);
        if(count == null){
            //第一次发送
            jedis.setex(countKey, 24*60*60, "1");
        }else if(Integer.parseInt(count)<=2){
            //发送次数加1
            jedis.incr(countKey);
        }else{
            //发送三次,不能发送
            System.out.println("今天发送次数已经超过三次");
            jedis.close();
            return;
        }

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

    }

    public static void getRedisCode(String phone, String code){
        Jedis jedis = new Jedis("192.168.189.128", 6379);
        //验证码key
        String codeKey = "Verifycode" + phone + "code";
        //从jedis获取验证码
        String redisCode = jedis.get(codeKey);
        if(redisCode.equals(code)){
            System.out.println("success");
        }else{
            System.out.println("fail");
        }
        jedis.close();
    }

    public static void main(String[] args) {
        //模拟验证码发送
        verifyCode("134567");

        getRedisCode("134567", "658404");

    }
}