要求:

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

分析:

  1. 随机生成6位数数字码: 使用Ramdom
  2. 验证码2分钟有效: 将验证码存到redis中设置120秒过期时间
  3. 判断验证码是否正确:取出redis中存的验证码是否和输入验证码一致
  4. 每个手机号只能发送3次: 使用redis中incr方法将次数自增1,判断大于2提交不能发送

实现代码:

首先要先加入jedis依赖

package com.xly.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * 模拟验证码发送
 */
public class PhoneCode {
    public static void main(String[] args) {
    	//模拟调用方法获得用户输入手机号/验证码
        String phone="13012345678";
        String code="123456";
        
        //模拟验证码发送
        verifyCode(phone);
        //验证
        getRedisCode(phone,code);

    }
    //1.生成6位数字验证码
    public static String getCode(){
        Random random = new Random();
        String code="";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code+=rand;
        }
        return code;
    }
    
    //2.每个手机每天只能发送3次,验证码放到redis中,设置过期时间2分钟
    public static void verifyCode(String phone){
        //链接redis
        Jedis jedis=new Jedis("192.168.56.10",6379);
        //拼接key
        //手机发送次数
        String countKey="VerifyCode"+phone+":count";
        //验证码
        String codeKey="VerifyCode"+phone+":code";

        //验证发送次数   每个手机每天只能发送3次
        String count = jedis.get(countKey);
        if(count==null){
            //未发送过 设置发送次数为1、时间1天内过期
            jedis.setex(countKey,24*60*60,"1");
        }else if(Integer.parseInt(count)<=2){
            //发送次数+1
            jedis.incr(countKey);
        }else{
            //大于3次
            System.out.println("今天发送次数大于三次");
            jedis.close();
            //退出方法,否则会继续发送验证码
            return;
        }
        //将验证码放到redis中,120秒过期
        String vcode=getCode();
        jedis.setex(codeKey,120,vcode);
        jedis.close();

    }
    //验证码校验
    public static void getRedisCode(String phone,String code){
        //链接redis
        Jedis jedis=new Jedis("192.168.56.10",6379);
        //验证码
        String codeKey="VerifyCode"+phone+":code";
        if (jedis.get(codeKey).equals(code)) {
            System.out.println("验证成功");
        }else{
            System.out.println("验证码错误");
        }
        jedis.close();
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐