package com.it.jedis;
import redis.clients.jedis.Jedis;
import java.util.Random;
//模拟手机验证码的发送
public class PhoneCode {
public static void main(String[] args) {
// verifyCode("14430202020");
getRedisCode("14430202020","908593");
}
//3.验证码校验
public static void getRedisCode(String phone,String code){
//连接redis
Jedis jedis = new Jedis("192.168.93.130", 6379);
//验证码key
String codeKey="verifyCode"+phone+"code";
String redisCode= jedis.get(codeKey);
//
if (redisCode.equals(code)){
System.out.println("成功");
}else {
System.out.println("失败");
}
}
//2.每个手机每天只能发送三次, 验证码放到redis中,设置过期时间
public static void verifyCode(String phone){
//连接redis
Jedis jedis = new Jedis("192.168.93.130", 6379);
//拼接key
//手机发送次数key
String phoneKey="verifyCode"+phone+"count";
//验证码key
String codeKey="verifyCode"+phone+"code";
String count = jedis.get(phoneKey);
if (count==null){
//如果redis中没有记录次数, 就是没有发送过, 设置次数为1
jedis.setex(phoneKey,24*60*60,"1");
}else if (Integer.parseInt(count)<=2){
//如果查询到次数小于等于2, 那么次数加1
jedis.incr(phoneKey);
} else {
System.out.println("今日验证码发送次数已达上限");
}
//发送验证码放到redis里面
String vccode = getCode();
jedis.setex(codeKey,120,vccode);
//关闭连接
jedis.close();
}
public static String getCode(){
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
int ran = random.nextInt(10);
sb.append(ran);
}
return sb.toString();
}
}
redis模拟手机验证码的发送验证过程
最新推荐文章于 2023-02-10 11:38:48 发布