添加jedis依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
1 public class jedisdemo1 { 2 public static void main(String[] args) { 3 //模拟验证码发送 4 verifyCode("12345678910"); 5 Scanner input=new Scanner(System.in); 6 String usercode = input.nextLine(); 7 getVerifyCode("12345678910",usercode); 8 9 } 10 11 //1.生成6位数字随机数 12 public static String getcode(){ 13 Random random = new Random(); 14 String code = ""; 15 for (int i=0;i<6;i++){ 16 //随机数取值范围为10 17 int rand = random.nextInt(10); 18 code += rand; 19 } 20 return code; 21 } 22 //2.每个手机每天只能发送3次,验证码放入redis,设置过期时间 23 public static void verifyCode(String phone){ 24 //创建Jedis对象 25 Jedis jedis = new Jedis("114.116.246.5",6379); 26 //设置连接使用密码 27 jedis.auth("Atcomsn1314"); 28 //测试是否连接 29 String value = jedis.ping(); 30 System.out.println(value); 31 //拼接key 32 //手机发送次数的key 33 String countkey = "VerifyCode"+phone+":count"; 34 //验证码的key 35 String codekey = "VerifyCode"+phone+":code"; 36 37 //每个手机每天只能发三次 38 String count = jedis.get(countkey); 39 if(count==null){ 40 //第一次发送 41 jedis.setex(countkey,24*60*60,"1"); 42 //验证码放入redis中 43 String vcode = getcode(); 44 jedis.setex(codekey,120,vcode); 45 }else if(Integer.parseInt(count)<=2){ 46 //二三次发送 47 //发送次数+1 48 jedis.incr(countkey); 49 //验证码放入redis中 50 String vcode = getcode(); 51 jedis.setex(codekey,120,vcode); 52 }else if(Integer.parseInt(count)>2){ 53 //发送三次,不能再发送 54 System.out.println("今天已发送三次,不会再发送"); 55 } 56 57 58 //查看次数和验证码 59 String countvalue = jedis.get(countkey); 60 String codevalue = jedis.get(codekey); 61 System.out.println("验证码:"+codevalue+"--次数:"+countvalue); 62 63 jedis.close();; 64 } 65 //3.验证码校验 66 public static void getVerifyCode(String phone,String code){ 67 //创建Jedis对象 68 Jedis jedis = new Jedis("114.116.246.5",6379); 69 //设置连接使用密码 70 jedis.auth("Atcomsn1314"); 71 //拼接key 72 //获取对应验证码key的value 73 String codekey = "VerifyCode"+phone+":code"; 74 String codevalue = jedis.get(codekey); 75 //判断验证码是否与输入值相同 76 if(codevalue.equals(code)){ 77 System.out.println("验证成功"); 78 }else { 79 System.out.println("验证失败"); 80 } 81 jedis.close(); 82 } 83 }View Code