此次代码仅适合初学者进行学习Redis,能够初步的掌握Redis在ideal中的基本操作,代码简单易懂
原理
- 生成随机的验证码。可以通过java的Random随机函数进行产生
- 建立函数生成key ,设置Redis设置过期时间,并将key值与验证码写入到Redis中
- 读取生成的验证进行校验
代码实现
创建maven项目 配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>redisTest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
- 生成随机的六位数验证码
public static String getCode(){
Random random = new Random();
String code="";
for(int i=0;i<6;i++){
int rand = random.nextInt(10);
code+=rand;
}
return code ;
}
- 将验证码写入到Redis中,并设定过期时间(2分钟),每天只能生成三次验证码
public static void verifyCode(String Phone){
Jedis jedis = new Jedis("niit02", 7001);
String CountKey="verify"+Phone+":count";
String CodeKey="verify"+Phone+":code";
String count = jedis.get(CodeKey);
if(count==null){
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();
}
String code = getCode();
jedis.setex(CodeKey,120,code);
jedis.close();
}
- 验证手机号和验证码
public static void getRdisCode (String Phone,String Code){
Jedis jedis = new Jedis("niit02", 7001);
String CodeKey="verify"+Phone+":code";
String redisCode = jedis.get(CodeKey);
System.out.println(redisCode);
if(redisCode.equals(Code)){
System.out.println("成功");
}else {
System.out.println("失败");
}
jedis.close();
}
- 主函数调用
public static void main(String[] args) {
getRdisCode("15182021426","756430");
}
|