环境准备:虚拟机Linux系统,redis安装在虚拟机中。
前提条件:虚拟机开启、redis开启。需要在pom中加入jedis依赖
1、代码
package com.jedis;
import redis.clients.jedis.Jedis;
import java.util.Random;
public class JedisTestRedis {
public static void main(String[] args) {
//模拟发送
verifyCode("18548375642");
// getReidsCode("18548375642","11684");
// System.out.println(getRandom());
}
//3、验证验证码
public static void getReidsCode(String phone,String code){
//连接redis
Jedis jedis = new Jedis("虚拟机地址",6379);
jedis.auth("123456");
//验证码
String codeKey = "verifyCode"+phone+"code";
String redisCode = jedis.get(codeKey);
//判断
if(redisCode.equals(code)){
System.out.println("成功");
}else{
System.out.println("失败");
}
jedis.close();
}
public static void verifyCode(String phone){
//连接redis
Jedis jedis = new Jedis("虚拟机地址",6379);
jedis.auth("123456");
//手机发送次数key
String countKey = "verifyCode"+phone+"count";
//验证码
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){
System.out.println("发送次数已经达到三次");
jedis.close();
return;
}
//发送验证码放到redis中
String vcode = getRandom();
System.out.println(vcode);
jedis.setex(codeKey,120,vcode);
jedis.close();
}
//六位数验证码
public static String getRandom(){
Random random = new Random();
String code ="";
for(int i=0;i<6;i++){
int rand = random.nextInt(10);
code+=rand;
}
return code;
}
}