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();
}
}
手机验证码(java+redis)
最新推荐文章于 2024-04-18 16:41:43 发布