【Redis】使用Jedis操作Redis

Jedis介绍

  jedis就是集成了redis的一些命令操作,封装了redis的java客户端。

Jedis使用

  使用jedis需要引入jedis的jar包,下面提供了maven依赖

  jedis.jar是封装的包,commons-pool2.jar是管理连接的包

 1 <!-- https://mvnrepository.com/artifact/redis.clients/jedis 客户端-->
 2         <dependency>
 3             <groupId>redis.clients</groupId>
 4             <artifactId>jedis</artifactId>
 5             <version>2.9.0</version>
 6         </dependency>
 7 
 8         <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
 9         <dependency>
10             <groupId>org.apache.commons</groupId>
11             <artifactId>commons-pool2</artifactId>
12             <version>2.5.0</version>
13         </dependency>

  1、新建一个maven工程,引入上面的依赖,编写测试类,如下

  

 1 package com.test.jedis;
 2 
 3 import org.junit.Test;
 4 
 5 import redis.clients.jedis.Jedis;
 6 import redis.clients.jedis.JedisPool;
 7 import redis.clients.jedis.JedisPoolConfig;
 8 
 9 public class TestJedisDemo1 {
10 
11     /**
12      * 单实例连接redis数据库
13      * @Description TODO
14      * @author H__D
15      * @date 2018年7月5日
16      */
17     @Test
18     public void run1() {
19         
20         Jedis jedis = new Jedis("120.78.189.168", 6379);
21         jedis.set("sex", "男");
22         System.out.println(jedis.get("sex"));
23     }
24 
25     /**
26      * Jedis连接池
27      * @Description TODO
28      * @author H__D
29      * @date 2018年7月5日
30      */
31     @Test
32     public void run2() {
33         
34         // 1、设置连接池的配置对象
35         JedisPoolConfig config = new JedisPoolConfig();
36         // 设置池中最大的连接数量(可选)
37         config.setMaxTotal(50);
38         // 设置空闲时池中保有的最大连接数(可选)
39         config.setMaxIdle(10);
40         
41         // 2、设置连接池对象
42         JedisPool pool = new JedisPool(config, "120.78.189.168", 6379);
43         
44         // 3、从池中获取连接对象
45         Jedis jedis = pool.getResource();
46         System.out.println(jedis.get("sex"));
47         
48         // 4、连接池归还
49         jedis.close();
50     }
51 }

  

  2、编写连接池工具类

  

 1 package com.test.jedis;
 2 
 3 import redis.clients.jedis.Jedis;
 4 import redis.clients.jedis.JedisPool;
 5 import redis.clients.jedis.JedisPoolConfig;
 6 
 7 public class JedisUtils {
 8 
 9     // 1、定义一个连接池对象
10     private final static JedisPool POOL;
11 
12     static {
13         // 初始化
14         // 1、设置连接池的配置对象
15         JedisPoolConfig config = new JedisPoolConfig();
16         // 设置池中最大的连接数量(可选)
17         config.setMaxTotal(50);
18         // 设置空闲时池中保有的最大连接数(可选)
19         config.setMaxIdle(10);
20 
21         // 2、设置连接池对象
22         POOL = new JedisPool(config, "120.78.189.168", 6379);
23     }
24     
25     /**
26      * 从连接池中获取连接
27      * @Description TODO
28      * @author H__D
29      * @date 2018年7月5日
30      * @return
31      */
32     public static Jedis getJedis() {
33         return POOL.getResource();
34     }
35 }

  

猜你喜欢

转载自www.cnblogs.com/h--d/p/9269887.html