package com.gao.peng;
import org.apache.commons.lang3.ObjectUtils;
import redis.clients.jedis.Jedis;
import java.util.Random;
import java.util.Scanner;
public class verifyDem01 {
public static void main(String[] args) {
//String code = verifyCode();
Scanner sc = new Scanner(System.in);
String phone_num = sc.nextLine();
int num = phone(phone_num);//判断手机号次数,以及存入验证码,并且返回手机的状态,0是可以继续,1次数用完
if (num == 0){
String code = creatCode(phone_num);
System.out.println(code);
String verifyCode = sc.nextLine();//输入验证码
verificationCode(phone_num + "codekey", verifyCode);
}else {
System.out.println("手机次数已用完");
}
}
//生成6位的验证码
public static String verifyCode(){
String code = "";
Random r = new Random();
int num;
for (int i = 0; i < 6; i++){
num = r.nextInt(10);
code += num;
}
return code;
}
//将手机号放到redis中,如果手机号作为key,判断key对应的value(手机号的输入的次数)的值,
//如果有次数,那么我们就判断是否是大于3,大于则提示次数已经用完,如果小于3则加1,
// 如果次数为空,那么就将手机号作为key,放到redis中,并且次数加1
public static int phone(String phone){
int codeStatus = 0;
Jedis jedis = new Jedis("127.0.0.1", 6379);
//先判断手机号是否是在redis中,我们取出key对应的value,
// 如果value是null就是redis中没有这个手机号
String phoneNumKey = "User" + phone + "Key";
String s = jedis.get(phoneNumKey);
if (ObjectUtils.isEmpty(s)){
jedis.setex(phoneNumKey, 60*60*24, "1");
} else if (Integer.parseInt(s) < 3) {
//给对应的手机号的次数加1
jedis.incr(phoneNumKey);
} else if (Integer.parseInt(s) >= 3) {
//如果次数是大于等于3,那么就输出次数已经用完
//System.out.println("今日次数已经用完,请24小时之后再试");
codeStatus = 1;
}
/*String code = verifyCode();//生成验证码
String phoneCode = phone + "codekey";
jedis.setex(phoneCode, 120, code);//将验证码放到redis中*/
jedis.close();
//return code;//返回验证码
return codeStatus;
}
public static String creatCode(String phone){
Jedis jedis = new Jedis("127.0.0.1", 6379);
String code = verifyCode();//生成验证码
String phoneCode = phone + "codekey";
jedis.setex(phoneCode, 120, code);//将验证码放到redis中
jedis.close();
return code;
}
//判断验证码是否正确,传入的参数是手机验证码和用户输入的验证码
public static void verificationCode(String phoneCode, String code){
//取出redis中的手机号对应的验证码
Jedis jedis = new Jedis("127.0.0.1", 6379);
String s = jedis.get(phoneCode);//取出对应的验证码
if (ObjectUtils.notEqual(s, code)){
//如果不相等就输出一句话
System.out.println("您输入的验证码错误");
}else {
System.out.println("验证码正确");
}
jedis.close();
}
}
使用Redis存储手机验证码,验证码有效期是120秒,一个手机号一天只能使用3次,代码如上。 欢迎大佬前来拍砖。