import redis.clients.jedis.Jedis;
import java.util.Random;
import java.util.Scanner;
/**
* 手机验证码功能
* 要求:
* 1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
* 2、输入验证码,点击验证,返回成功或者失败
* 3、每个手机号每天只能输入三次
*/
public class PhoneVerification {
private static final Jedis jedis=new Jedis("192.168.111.130",6379);
/**
* 模拟验证码
*/
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String phone =scanner.nextLong() + "";//用户输入的手机号
PutYanZhengMa(phone);//验证码放进redis
String usernum = scanner.nextLong() + "";//用户输入的验证码
Verify(phone, usernum);//验证
}
/**
* 验证是否正确
*/
public static void Verify(String phone,String num){
String codePhone="Verify"+phone+"code";//手机收验证码的key
if (num.equals(jedis.get(codePhone))) {
//正确
System.out.println("成功");
}
else {
System.out.println("失败");
}
}
/**
* 每个手机每天只能发三次,每个验证码120s==2分min有效时间
* @param phone 手机号
*/
public static void PutYanZhengMa(String phone){
String codePhone="Verify"+phone+"code";//手机收验证码的key
String codeTime="Verify"+phone+"count";//手机收验证码次数的key
String count=jedis.get(codeTime);//该手机号今天获取验证码的次数
if (count==null) {
//没有就开始设置它的属性
jedis.setex(codeTime,60*60*24,"1");
}
else if (Integer.parseInt(count)<=2){
//已经有了,但没超,直接+1
jedis.incr(codeTime);
}
else {
System.out.println("已达三次了");
return;
}
int nums= new Random().nextInt(1000000);//随机生成的6位数字验证码,
jedis.setex(codePhone,120,nums+"");
System.out.println("发送的验证码为"+nums+",2分钟后失效");
}
}
Redis模拟2分钟有效验证码
猜你喜欢
转载自blog.csdn.net/wflsyf/article/details/116498474
今日推荐
周排行