手机验证码
1 需求
- 六位随机数字,两分钟内有效
- 输入验证码,进行验证
- 一天只能请求三条验证码
2 思路
-
生成六位随机数字 通过random实现
-
验证码两分钟内有效 验证码放到redis中,expire
-
比较是否一致 拿到redis中进行比较
-
一天只能发送三条 incr设置大于2就不能发送了
3 实现
3.1 依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
3.2 代码
package com.xzzlx;
import redis.clients.jedis.Jedis;
import java.util.Random;
public class PhoneCode {
public static void main(String[] args) {
verifyCode("17888888888");
// getRedisCode("17888888888", "290782");
}
/**
* 生成6位随机数字验证码
* @return 随机数字验证码
*/
public static StringBuffer getCode(){
StringBuffer code = new StringBuffer();
Random random = new Random();
for (int i = 0; i < 6; i++) {
int num = random.nextInt(10);
code.append(num);
}
return code;
}
/**
* 验证今天是否已经发送3次了
* 验证码放到redis中,设置过期时间
* @param phone 手机号
*/
public static void verifyCode(String phone){
Jedis jedis = new Jedis("192.168.17.135", 6379);
// 手机发送次数
String countKey = "VerifyCode" + phone + ":count";
// 验证码key
String codeKey = "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) {
// 发送次数加1
jedis.incr(countKey);
}else if (Integer.parseInt(count) > 2){
// 今天已经发送3次了,不能再发送了
System.out.println("今天已经发送三次了");
jedis.close();
}
StringBuffer vcode = getCode();
jedis.setex(codeKey, 120, String.valueOf(vcode));
jedis.close();
}
/**
* 验证码得校验
* @param phone
* @param code
*/
public static void getRedisCode(String phone, String code){
Jedis jedis = new Jedis("192.168.17.135", 6379);
// 手机验证码
String codekey = "VerifyCode" + phone + ":code";
String redisCode = jedis.get(codekey);
System.out.println("验证码是:" + redisCode);
System.out.println("输入的是:" + code);
System.out.print("验证");
if (redisCode.equals(code)){
System.out.print("成功");
}else {
System.out.print("失败");
}
jedis.close();
}
}
3.3 测试
3.3.1
启动项目,先注释掉第十行,然后运行
3.3.2
然后去redis中查看
keys *
getVerifyCode1788888888:count
getVerifyCode1788888888:code
3.3.3
注释掉第九行,将第十行打开,然后输入手机号和getVerifyCode1788888888:code
得到的验证码即可
该Demo是按照尚硅谷的老师视频打出来的,视频链接是https://www.bilibili.com/video/BV1Rv41177Af有问题可以call我