栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

手机验证码(java+redis)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

手机验证码(java+redis)

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

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


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();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/459079.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号