Redis——模拟手机验证码校验过程
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.util.Random;
/**
* @author huangdh
* @version 1.0
* @description:
* @date 2022-09-21 7:51
*/
@Slf4j
public class PhoneVerificationCode {
/**
* verification code
* auth code:授权码
* security code:安全码,验证码
* identifying code:参考代码;标识码;验证码;
*/
public static void main(String[] args) {
// 模拟手机发送验证码
verifyCode("18886033098");
getReidsCode("18886033099","222138");
}
public static void getReidsCode(String phone, String code){
JedisShardInfo shardInfo = new JedisShardInfo("8.8.80.8",6379);
shardInfo.setPassword("@#$***");
Jedis jedis = new Jedis(shardInfo);
// 验证码key
String codeKey = "VerifyCode" + phone + ":code";
String redisCode = jedis.get(codeKey);
if (redisCode.equals(code)){
System.out.println("手机验证码成功!");
}else {
System.out.println("手机验证码失败!");
}
jedis.close();
}
/**
* 每个手机每天只能发送三次,验证码放到redis中,并设置过期时间
* @param phone:手机号码
*/
public static void verifyCode(String phone){
JedisShardInfo shardInfo = new JedisShardInfo("8.8.80.8",6379);
shardInfo.setPassword("@#$***");
Jedis jedis = new Jedis(shardInfo);
// 拼接key
// 手机发送次数key
String countKey = "VerifyCode" + phone + ":count";
// 验证码key
String codeKey = "VerifyCode" + phone + ":code";
// 首先判断该手机号码是否发送过
String count = jedis.get(codeKey);
if (count == null){
// 没有发送过,将改手机号放入redis中,并设置发送次数为1
jedis.setex(countKey,24*60*60,"1");
}else if (Integer.parseInt(count) <=2){
// 发送次数+1
jedis.incr(codeKey);
}else if (Integer.parseInt(count) >2){
System.out.println("今天改手机号发送次数已经超过3次,请明天在进行验证!");
jedis.close();
}
// 生成验证码并放入到redis中
String generateCode = generateCode();
jedis.setex(codeKey,120,generateCode);
jedis.close();
}
/**
* 生成6位随机验证码
* @return
*/
public static String generateCode(){
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 6; i++) {
int code = random.nextInt(10);
stringBuilder.append(code);
}
return stringBuilder.toString();
}
}