05jedis操作测试

一.什么是jedis

首先我们知道在CentOS系统中我们安装的redis目录下的bin目录存在这些文件。

 

 而且,redis-cli是我们在linux系统上对redis进行操作的客户端。那么我们想要在进行java开发的时候操作我们的redis,那么jedis就是java平台的操作redis的客户端了。

 

二.在java平台对Redis进行操作

第一步,首先我们创建一个Maven项目,导入依赖后。我们就可以对本机的Redis或者是远程的Redis进行操作了。

 

 第二部,编写代码

1 Jedis jedis = new Jedis(host,port);
2 jedis.auth(password);

第三步,使用jedis对象调用ping()方法。查看是否返回pong,若返回则连接正常,可以进行想要的操作了。

第四步,在这里我们就可以使用jedis对象对Redis进行各种操作了。

 

三.使用jedis模拟手机验证码发送案例

 1 public class MobilePhoneVerificationCode {
 2 
 3 
 4     @Test
 5     public void getCode(){   //获取验证码
 6         String phone = "13240260325";
 7         verifyCode(phone);
 8     }
 9     @Test
10     public void  login(){
11         String phone ="13240260325";
12         String code = "";  //这里查看控制台输出的验证码
13         checkCode(phone,code);
14     }
15 
16 
17 
18     //生成一个自定个数的验证码
19     public static String generateCode(){
20         StringBuilder code = new StringBuilder();
21         Random random = new Random();
22         for (int i = 0; i < 6; i++) {
23             int r = random.nextInt(10);
24             code.append(r);
25         }
26         return code.toString();
27     }
28 
29     //检查判断今天是否超过3次发送验证码,将验证码放入redis中,并设置过期时间
30     public static void verifyCode(String phone){
31         Jedis jedis = new Jedis("host",port);
32         jedis.auth("password");
33         //redis中的key
34         String codeKey = phone+"code";
35         String countKey = phone+"count";
36 
37         String count = jedis.get(countKey);//获取当前手机号当天的发送验证码次数
38         if(count==null){
39             //一次都没发送过,Redis不存在该key
40             jedis.setex(countKey,24*60*60L,"1");
41         }else if (Integer.parseInt(count) <=2){
42             //发送了1次或者2次
43             jedis.incr(countKey);
44         }else if(Integer.parseInt(count)>2){
45             //已经发送了3次
46             System.out.println("今天的发送已经达到3次");
47             jedis.close();
48             return;
49         }
50         String vCode = generateCode();
51         System.out.println("生成的验证码为:"+vCode);
52         jedis.setex(codeKey,60L,vCode);//发送的验证码要放到redis中
53         jedis.close();
54     }
55 
56     //验证码校验
57     public static void checkCode(String phone,String code){
58         String codeKey = phone+"code";
59         Jedis jedis = new Jedis("host",port);
60         jedis.auth("password");
61         String rCode = jedis.get(codeKey);
62         if(rCode.equals(code)){
63             System.out.println("验证码正确");
64         }else{
65             System.out.println("验证码错误");
66         }
67         jedis.close();
68     }
69 
70 }

 

posted @ 2021-07-18 15:23  Costin  阅读(80)  评论(0)    收藏  举报