Jedis案例-模拟验证码发送
package com.jedisDemo1;
import redis.clients.jedis.Jedis;
/**
* @author Jacob
* @create 2022-06-27 9:04
*/
public class VerificationCode {
public static void main(String[] args) {
//Verify("15120142316");
getVericode("15155555", "585262");
}
//1.随机6位验证码
public static String RamdomVericationCode() {
//int value = (int) (Math.random() * (999999 - 100000 + 1) + 100000);//得到[a,b]闭区间的随机数
String Verification = "";
for (int i = 0; i < 6; i++) {
int value = (int) (Math.random() * 10);//随机数0-1
Verification += value;
}
return Verification;
}
//2.设置过期时间120s/expire key 用户每天只能申请3次验证码
public static void Verify(String phone) {
//计数的key和验证码key的规则拼接
String countKey = "VericationCode" + phone + ":count";
String verifyKey = "VericationCode" + phone + ":verify";
//把key放入Reids中设置一条最多三次
//连接redis
Jedis jedis = new Jedis("127.0.0.1", 6379);
//根据key获取value
String count = jedis.get(countKey);
if (count == null) {
//如果等于null说明还没有往redis中放入
//设置键值的同是设置过期时间
jedis.setex(countKey, 24 * 60 * 60, "1");
} else if (Integer.parseInt(count) <= 2) {
jedis.incr(countKey);//value增1
} else if (Integer.parseInt(count) >= 3) {
System.out.println("今日的发送次数已经超过3次!!");
return;
}
//把验证码放入reids中
//获取验证码
String vcode = RamdomVericationCode();
jedis.setex(verifyKey, 120, vcode);
//关闭jedis
jedis.close();
}
//3.校验验证码
public static void getVericode(String phone, String code) {
//连接jedis
Jedis jedis = new Jedis("127.0.0.1", 6379);
String verifyKey = "VericationCode" + phone + ":verify";
String codeKey = jedis.get(verifyKey);//根据形参phone拿对应的code
if (codeKey.equals(code)) {
System.out.println("成功!");
} else {
System.out.println("失败!");
}
}
}
打开这个方法获取验证码,获取验证码的时候打印栏没提示
Redis中查看获取的验证码(有效期2分钟)和验证次数(每天只能3次)
第一次,count是1,验证码083875
验证码校验
打开这个方法校验,正确则打印成功,错误则打印失败
一天不能超过3次验证码请求