Redis存储手机验证码,进行校验
package com.qst.jedis;
import redis.clients.jedis.Jedis;
import java.util.Random;
public class PhoneCode {
//虚拟机中redis地址
public static Jedis jedis = new Jedis("192.168.218.121",6379);
public static void main(String[] args) {
VerifyCode("1667398XXXX");
// getRedisCode("16673985996","75785");
}
public static void getRedisCode(String phone,String code){
//redis数据库密码
jedis.auth("123456");
String countCode="VerifyCode"+phone+":code";
String c = jedis.get(countCode);
if (c.equals(code)){
System.out.println("校验成功");
}else {
System.out.println("校验失败");
}
jedis.close();
}
//每个手机每天只能发送三次,验证码放到redis中,设置过期时间
public static void VerifyCode(String phone){
jedis.auth("123456");
//生成存放手机号次数的key
String countKey="VerifyCode"+phone+":count";
String countCode="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){
jedis.incr(countKey);
}else if (Integer.parseInt(count)>2){
System.out.println("发送次数超过三次");
jedis.close();
return;
}
//写入验证码到redis
String s = getCode();
jedis.setex(countCode,120,s);
jedis.close();
}
//生成随机6位数验证码
public static String getCode(){
StringBuilder code=new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
int nextInt = random.nextInt(10);
code.append(nextInt);
}
return code.toString();
}
}