使用jedis模拟手机验证码发送
原创
©著作权归作者所有:来自51CTO博客作者不断前进的皮卡丘的原创作品,请联系作者获取转载授权,否则将追究法律责任
✨ 使用jedis模拟手机验证码发送
📃个人主页:不断前进的皮卡丘
🌞博客描述:梦想也许遥不可及,但重要的是追梦的过程,用博客记录自己的成长,记录自己一步一步向上攀登的印记
🔥个人专栏:微服务专栏
需求分析
代码实现
生成随机验证码
/**
* 生成六位数字验证码
*/
public static String getCode(){
Random random = new Random();
String code="";
for (int i = 0; i < 6; i++) {
int randNumber=random.nextInt(10);
code+=randNumber;
}
return code;
}
限制手机发送验证码次数,把验证码存储在redis,并且设置有效时间
/**
* 每一个手机每天只能发送3次验证码,并且我们要把验证码存储到redis中,并且要设置过期时间
*/
public static void verifyCode(String phone){
//连接redis
Jedis jedis = new Jedis("10.100.173.128", 6379);
//操作redis
//手机发送次数key
String countKey="VerifyCode"+phone+":count";
//验证码key
String codeKey="VerifyCode"+phone+":code";
//每一个手机,一天最多发送三次验证码
String count = jedis.get(countKey);
if (count==null){
//说明是第一次发送
//设置发送次数为1
jedis.setex(countKey,24*60*60,"1");
}else if (Integer.parseInt(count)<=2){
//发送次数+1
jedis.incr(countKey);
}else{
System.out.println("今天发送次数已经到达三次了,不可以再发送了");
//释放连接
jedis.close();
return;
}
//把验证码存储在redis中
String vCode = getCode();
jedis.setex(codeKey,120,vCode);
jedis.close();
}
验证码的校验
/**
* 验证码的校验
*/
public static void getRedisCode(String phone,String code){
Jedis jedis = new Jedis("10.100.173.128", 6379);
//从redis中获取验证码,然后和用户输入的验证码进行比较
//验证码key
String codeKey="VerifyCode"+phone+":code";
String redisCode = jedis.get(codeKey);
//判断
if (redisCode.equals(code)){
System.out.println("验证成功");
}else {
System.out.println("验证失败");
}
jedis.close();
}
测试