码迷,mamicode.com
首页 > 其他好文 > 详细

Jedis使用

时间:2018-04-29 01:27:56      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:dep   his   valueof   set   source   style   spring   warning   conf   

Jedis是java调用Redis的接口。

一。Maven中的jedis依赖包

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>

二。配置redis.properties.xml

 1 # *************** jedis connection parameters setting ************** #
 2 # redis server ip #
 3 redis.ip=127.0.0.1
 4 # redis server port #
 5 redis.port=6379
 6 # password
 7 redis.password=redis123
 8 
 9 # *************** jedis pool parameters setting ************** #
10 # jedis‘s max connected objects #
11 redis.pool.maxTotal=1000
12 # jedis‘s max saved idel objects #
13 redis.pool.maxIdle=10
14 # jedis‘s max waiting time when no object returnd #
15 redis.pool.maxWaitMillis=5000
16 # whether test when jedis is calling borrowObject() #
17 redis.pool.testOnBorrow=true
18 # whether test when jedis is calling returnObject() #
19 redis.pool.testOnReturn=true

三。编写JAVA类获取Jedis连接池

 1 import redis.clients.jedis.Jedis;
 2 import redis.clients.jedis.JedisPool;
 3 import redis.clients.jedis.JedisPoolConfig;
 4 
 5 import java.io.IOException;
 6 import java.util.Properties;
 7 
 8 /**
 9  * Created by XA on 2017/11/6.
10  */
11 public class MyJedisPool {
12 
13     private volatile static JedisPool pool;
14     private static Jedis jedis;
15 
16     private static JedisPool getJedisPool() {
17         if(pool==null) {
18             synchronized (MyJedisPool.class) {
19                 if(pool==null) {
20                     try{
21                         Properties props = new Properties();
22                         props.load(MyJedisPool.class.getClassLoader().getResourceAsStream("config/redis.properties"));
23                         // create jedis pool instance
24                         JedisPoolConfig config = new JedisPoolConfig();
25                         // set property items of jedis pool
26                         config.setMaxTotal(Integer.valueOf(props.getProperty("redis.pool.maxTotal")));
27                         config.setMaxIdle(Integer.valueOf(props.getProperty("redis.pool.maxIdle")));
28                         config.setMaxWaitMillis(Integer.valueOf(props.getProperty("redis.pool.maxWaitMillis")));
29                         config.setTestOnBorrow(Boolean.valueOf(props.getProperty("redis.pool.testOnBorrow")));
30                         config.setTestOnReturn(Boolean.valueOf(props.getProperty("redis.pool.testOnReturn")));
31                         // instance
32                         pool = new JedisPool(config, props.getProperty("redis.ip"), Integer.valueOf(props.getProperty("redis.port")), 5000, props.getProperty("redis.password"));
33 
34                     }catch (IOException e) {
35                         e.printStackTrace();
36                     }
37                 }
38             }
39         }
40         return pool;
41     }
42 
43     // get jedis
44     public static Jedis getJedis() {
45         return getJedisPool().getResource();
46     }
47 
48     // recycle jedis
49     public synchronized static void recycleJedis(Jedis jedis) {
50         if(jedis!=null) {
51             jedis.close();
52         }
53     }
54 }

四。使用jedis的常用示例

public static void main(String[] args){
        try{
            Jedis jedis = MyJedisPool.getJedis();
            Set<String> keys = jedis.keys("*");
            System.out.println(keys.size());
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            MyJedisPool.recycleJedis(jedis);
        }
        
    }

注意:1. 不要忘记调用recycleJedis()回收jedis示例

   2. 实际调用recycleJedis()后发现,jedis仍然有效。原因暂时未知。

 

五。使用反射和泛型封装jedis的申请和回收

 1 @SuppressWarnings("unchecked")
 2     public static <T> T invokeJedisMethod(String methodName, Object[] args) {
 3         Jedis jedis = MyJedisPool.getJedis();
 4 
 5         T returnObject = null;
 6         try {
 7             Class[] argsTypes = new Class[args.length];
 8             for (int i = 0; i < args.length; i++) {
 9                 Class argClazz = args[i].getClass();
10                 if (argClazz.equals(HashMap.class)) {
11                     argsTypes[i] = Map.class;
12                 } else {
13                     argsTypes[i] = argClazz;
14                 }
15 
16             }
17             Method method = jedis.getClass().getDeclaredMethod(methodName, argsTypes);
18 
19             returnObject = (T) method.invoke(jedis, args);
20         } catch (Exception e) {
21             System.out.print(e.getStackTrace()[1].getClassName() + " --> " +
22                     e.getStackTrace()[1].getMethodName() + " --> " +
23                     e.getClass().getName() + "\n");
24             e.printStackTrace();
25         } finally {
26             MyJedisPool.recycleJedis(jedis);
27         }
28         return returnObject;
29     }

运行测试:


 1 import org.junit.Assert;
 2 import org.junit.Test;
 3 import org.springframework.test.annotation.Rollback;
 4 import org.springframework.transaction.annotation.Transactional;
 5 
 6 import java.util.HashMap;
 7 import java.util.List;
 8 import java.util.Map;
 9 import java.util.Set;
10 
11 public class JedisServiceTest {
12 
13     public enum CommonAPI {
14         // keys
15         keys("keys", 1), del("del", 20), exists("exists", 22),
16         // hash
17         hget("hget", 2), hgetAll("hgetAll", 3), hset("hset", 4), hmset("hmset", 5), hlen("hlen", 6), hexists("hexists", 7), hdel("hdel", 8), hkeys("hkeys", 9), hmget("hmget", 23),
18         // zsort
19         zadd("zadd", 10), zrem("zrem", 11), zrange("zrange", 12), zcard("zcard", 13), zcount("zcount", 14),
20         // list
21         linsert("linsert", 15), llen("llen", 16), lpop("lpop", 17), lpush("lpush", 18), lrange("lrange", 19),
22         // sub-pub
23         subscribe("subscribe", 21);
24 
25         private String name;
26         private int index;
27 
28         CommonAPI(String name, int index) {
29             this.name = name;
30             this.index = index;
31         }
32 
33         public String getName() {
34             return name;
35         }
36     }
37 
38     /**
39      * 事务回滚无效,redis并不支持可回滚的事务
40      */
41     @Test
42     @Transactional
43     @Rollback
44     public void invokeJedisMethod() {
45 
46         // 1
47         JedisService.invokeJedisMethod(JedisService.CommonAPI.hset.getName(),  new Object[]{"key1", "hkey1", "value1"});
48         Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key1"));
49         Set<String> keys = JedisService.invokeJedisMethod(JedisService.CommonAPI.keys.getName(), "key1");
50         Assert.assertTrue(keys.contains("key1"));
51 
52         Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.hexists.getName(), new Object[] {"key1", "hkey1"}));
53         Set<String> hkeys = JedisService.invokeJedisMethod(JedisService.CommonAPI.hkeys.getName(), "key1");
54         Assert.assertTrue(hkeys.contains("hkey1"));
55 
56         Assert.assertEquals(JedisService.invokeJedisMethod(JedisService.CommonAPI.hget.getName(), new Object[] {"key1", "hkey1"}), "value1");
57 
58         JedisService.invokeJedisMethod(JedisService.CommonAPI.hdel.getName(), new Object[] {"key1", new String[]{"hkey1"}});
59         Assert.assertFalse(JedisService.invokeJedisMethod(JedisService.CommonAPI.hexists.getName(), new Object[] {"key1", "hkey1"}));
60 
61         JedisService.invokeJedisMethod(JedisService.CommonAPI.del.getName(), "key1");
62         Assert.assertFalse(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key1"));
63 
64         // 2
65         Map<String, String> map = new HashMap<String, String>();
66         map.put("hkey1", "hvalue1");map.put("hkey2", "hvalue2");
67         JedisService.invokeJedisMethod(JedisService.CommonAPI.hmset.getName(), new Object[] {"key2", map});
68         Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key2"));
69         Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.hexists.getName(), new Object[] {"key2", "hkey2"}));
70         Assert.assertEquals(JedisService.invokeJedisMethod(JedisService.CommonAPI.hget.getName(), new Object[] {"key2", "hkey2"}), "hvalue2");
71         Assert.assertEquals((long)JedisService.invokeJedisMethod(JedisService.CommonAPI.hlen.getName(), "key2"), map.size());
72 
73         Map<String, String> res = JedisService.invokeJedisMethod(JedisService.CommonAPI.hgetAll.getName(), "key2");
74         Assert.assertEquals(res.size(), map.size());
75 
76         List<String> hvalues = JedisService.invokeJedisMethod(JedisService.CommonAPI.hmget.getName(), new Object[] {"key2", map.keySet().toArray(new String[map.size()])});
77         Assert.assertEquals(hvalues.size(), 2);
78         Assert.assertTrue(hvalues.contains("hvalue1"));
79         Assert.assertTrue(hvalues.contains("hvalue2"));
80 
81         JedisService.invokeJedisMethod(JedisService.CommonAPI.del.getName(), "key2");
82         Assert.assertFalse(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key2"));
83 
84     }
85 
86 }

 


测试全部通过。

 

Jedis使用

标签:dep   his   valueof   set   source   style   spring   warning   conf   

原文地址:https://www.cnblogs.com/PigeonNoir/p/8969991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!