手机验证码(java+redis)

import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.io.OutputStream;
import java.util.Random;

/**
 * @auther cheng
 * @create 2021-11-09-13:34
 */
public class PhoneCode {
    @Test
    public void test1(){
        verifyCode("17852031111");
    }

    @Test
    public void test2(){
        getRedisCode("17852031111","790424");
    }
	
	//生成验证码(随机数)
    public static String getCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        return code;
    }

	//发送验证码
    public static void verifyCode(String phone){
    	//redis连接地址
        Jedis jedis = new Jedis("0.0.0.0",6379,0);
        //密码,没有可以省略
        jedis.auth("123456");
		
		//记录发送次数(设置每天三次)
        String countKey = phone+":count";
        //记录每次的验证码
        String codeKey = 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 if (Integer.parseInt(count)>2){
            System.out.println("今天验证次数超过三次");
            //关闭连接并返回
            jedis.close();
            return;
        }
		
		//少于三次执行:将验证码存到redis中
        String vcode = getCode();
        jedis.setex(codeKey,120,vcode);
        jedis.close();
        //此处可以将验证码发送给手机
    }
	
	//验证码判断
	//code为手机端输入的验证码
    public static void getRedisCode(String phone,String code){
    	//redis连接地址
        Jedis jedis = new Jedis("0.0.0.0",6379,0);
        //密码,没有可以省略
        jedis.auth("123456");
        //验证码的key
        String codeKey = phone+":code";
        //将要查询的redis中的验证码
        String redisCode = "";
        try {
        	//过期会异常
            redisCode = jedis.get(codeKey);
        }catch (Exception e){
            System.out.println("过期");
        }
        if (redisCode == null){
            System.out.println("过期");
        }else if (redisCode.equals(code)){
            System.out.println("成功");
        }else {
            System.out.println("错误");
        }
        jedis.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值