模拟Redis发验证码
模拟Redis发验证码
Java操作Redis
使用jedis可以对redis进行操作,但是得关闭保护模式
模拟验证码
- 输入手机号,点击后发送随机六位数验证码,2分钟内有效
- 输入验证码,点击验证,返回成功还是失败
- 每个手机号每天只能输入3次
实现流程
- 生成6位数字验证码, Random类
- 验证码2分钟内有效 放到redis中,设置过期时间120秒
- 判断验证码是否一致 从redis中取出验证码进行比较
- 每个手机号每天3次 incr 每次发送后+1
我们创建一个PhoneCode类,在这个类里面进行模拟
首先是生成验证码
生成六位验证码,可以调用Random类的NextInt函数,生成六个10以内的正整数,进行拼接
//生成六位验证码
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;
}
其次是让每个手机号每天只能发送三次,将验证码放到redis中去。
拿到一个电话号码,先到redis中查找是否对它记过数,没记过数,就设其发送一次,之后生成其对应的验证码放入redis,若已发送次数不到3,就重新生成验证码,放入redis,若次数已到3,就打印”今天已发送过三次“,并关闭连接。
//让每个手机每天只能发送三次,验证码放到redis中去,设置过期时间
public static void setCode(String phone){
Jedis jedis = new Jedis("101.37.13.45",6379);
String countKey = "VerifyCode"+phone+":count";
String codeKey = "VerifyCode"+phone+":code";
String count = jedis.get(codeKey);
if(count==null){ //如果手机号还没发过请求
jedis.setex(countKey,12*60*60,"1"); //对手机发送次数计时,有效期一天
}else if(Integer.parseInt(count)<=2){
jedis.incr(countKey);
}else if(Integer.parseInt(count)>2){
System.out.println("今天已发送过三次");
jedis.close();
}
String vCode = getCode();
jedis.setex(codeKey,120, vCode); //将手机号对应的验证码放入redis,设有效期120
jedis.close();
}
校验验证码
将验证码从redis中取出,和用户提交的验证码进行比对。
//校验验证码
public static void verifyCode(String phone, String code){
Jedis jedis = new Jedis("101.37.13.45",6379);
String codeKey = "VerifyCode"+phone+":code";
String redisCode = jedis.get(codeKey);
if(redisCode == null){
System.out.println("验证码已过期");
} else if(code.equals(redisCode)){
System.out.println("成功");
}else{
System.out.println("失败");
}
jedis.close();
}