使用redis模拟验证码发送
1、需求
1、输入手机号,点击发送后随机生成6位数字码,2分钟有效 2、输入验证码,点击验证,返回成功或失败 3、每个手机号每天只能输入3次
2、导入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
总体分为三步
// 1.生成6位数字验证码
// 2.每个手机号每天只能发送三次验证码,验证码放到redis中,设置过期时间为2min
// 3、校验验证码
3、生成6位数字验证码
public static StringBuffer getCode() {
StringBuffer code = new StringBuffer();
Random random = new Random();
for (int i=0; i<6;i++) {
int rand = random.nextInt(10);
code.append(rand);
}
return code;
}
4、设置验证码(难点)
怎么来实现验证码每天只能输入三次呢?
- 创建一个变量
countKey ,用来统计发送验证码的次数 - 计算当天的时间,距离第二天凌晨12点的秒数,设置为
countKey 的过期时间
计算时间差
public Long getRefreshTime() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
}
功能实现
public static void veriftCode(String phone) {
PhoneCode phoneCode = new PhoneCode();
Jedis jedis = new Jedis("192.168.154.65", 6379);
jedis.auth("123456");
String countKey = "VerifyCode" + phone + ":count";
String codeKey = "VerifyCode" + phone + ":code";
String count = jedis.get(countKey);
if (count == null || count == "") {
Long refreshTime = phoneCode.getRefreshTime();
jedis.setex(countKey, refreshTime, "1");
System.out.println("第" + jedis.get(countKey) + "次" + "验证码已发送,请耐心等待");
} else if (Integer.parseInt(count) <= 2) {
jedis.incr(countKey);
System.out.println("第" + jedis.get(countKey) + "次" + "验证码已发送,请耐心等待");
} else if (Integer.parseInt(count) > 2) {
System.out.println("今日已经发送超过三次,请明日再试");
jedis.close();
}
String code = getCode().toString();
Long expireTime = (long) 2 * 60;
jedis.setex(codeKey, expireTime, code);
jedis.close();
}
5、校验验证码
public static void getRedisCode(String phone, String code) {
Jedis jedis = new Jedis("192.168.154.65", 6379);
jedis.auth("123456");
String codeKey = "VerifyCode" + phone + ":code";
String redisCode = jedis.get(codeKey);
if(code.equals(redisCode)){
System.out.println("验证码输入正确");
}else{
System.out.println("验证码输入错误");
}
jedis.close();
}
6、测试
public static void main(String[] args) {
veriftCode("13923459867");
getRedisCode("13923459867", "784449");
}
|