1.基本要求

2.功能分析

3.完整代码
package com.redis.jedis;
import redis.clients.jedis.Jedis;
import java.util.Random;
//手机验证码模拟
public class phoneCode {
public static void main(String[] args) {
// //验证是否成功生成验证码
// String code1 = getCode();
// System.out.println(code1);
// 模拟验证码发送
verifyCode("1587263272");
// getRedisCode("1587263272","098017");
}
//1.生成6位数字验证码
public static String getCode() {
Random random = new Random();
String code = "";
for (int i = 0; i < 6; i++) {
int rand = random.nextInt(10);
code += rand;
}
return code;
}
//2.每个手机每天只能发3次,验证码放到redis中,设置过期时间
public static void verifyCode(String phone){
// 连接Redis
Jedis jedis = new Jedis("172.19.8.112", 6379);
// 拼接key
// 手机放送次数
String countKey="VerifyCode"+phone+":count";
// 验证码key
String codeKey="VerifyCode"+phone+":code";
// 每个手机每天只能发3次
String count=jedis.get(countKey);
if(count == null){
//表示没有发送过
//设置发送次数为1
jedis.setex(couKey,24*60*60,"1");
}else if(Integer.parseInt(count)<=2){
//发送次数+1
jedis.incr(countKey);
}else if(Integer.parseInt(count)>2){
//已经发送过3次
System.out.println("今天发送次数已经超过3次了");
jedis.close();
}
// 验证码放到redis中
String vcode = getCode();
jedis.setex(codeKey,120,vcode);
jedis.close();
}
//3.验证码验证
public static void getRedisCode(String phone,String code){
Jedis jedis = new Jedis("172.19.8.112", 6379);
String codeKey="VerifyCode"+phone+":code";
String redisCode = jedis.get(codeKey);
//判断
if(redisCode.equals(code)){
System.out.println("成功");
}else{
System.out.println("失败");
}
jedis.close();
}
}


这是一个Java程序,使用Jedis库与Redis进行交互,实现了生成6位数字验证码、限制每个手机号每天最多发送3次验证码以及验证码验证的功能。程序首先生成验证码,然后将发送次数和验证码存入Redis,并设置过期时间。最后,通过Redis验证输入的验证码是否正确。
&spm=1001.2101.3001.5002&articleId=116787712&d=1&t=3&u=f6feb13cef184fd28150cbcf9f609275)
2万+

被折叠的 条评论
为什么被折叠?



