今天試了一下Jedis裏鏈接池JedisPool的的使用。代碼以下:redis
package com.myapp.jedis.pooldemo; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Created by baidu on 16/10/18. */ public class TestPool { private static JedisPool pool = null; public static JedisPool getPool() { if (pool == null) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(500); config.setMaxIdle(5); config.setMaxWaitMillis(1000*10); //在borrow一個jedis實例時,是否提早進行validate操做;若是爲true,則獲得的jedis實例均是可用的; config.setTestOnBorrow(true); //new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); pool = new JedisPool(config, "[ip]", 8379, 10000, "[auth]"); } return pool; } public synchronized static Jedis getResource() { if (pool == null) { pool = getPool(); } return pool.getResource(); } // 返還到鏈接池 // Deprecated // 換成用完以後, redis.close() /* public static void returnResource(Jedis redis) { if (redis != null) { pool.returnResource(redis); } } */ public static void main(String[] args) { Jedis redis = null; int loop = 1; while (loop < 20) { try { long start = System.currentTimeMillis(); redis = getResource(); redis.set("k1", "v1"); String ret = redis.get("k1"); long end = System.currentTimeMillis(); System.out.printf("Get ret from redis: %s with %d millis\n", ret, end-start); } finally { if (redis != null) { redis.close(); } } loop++; } } }
其中,有個函數returnResource已經deprecated了,如今Jedis的close方法重寫了,用Jedis.close來釋放資源。app
跑了20次,運行結果以下:函數
Get ret from redis: v1 with 564 millis Get ret from redis: v1 with 235 millis Get ret from redis: v1 with 225 millis Get ret from redis: v1 with 214 millis Get ret from redis: v1 with 210 millis Get ret from redis: v1 with 232 millis Get ret from redis: v1 with 209 millis Get ret from redis: v1 with 211 millis Get ret from redis: v1 with 239 millis Get ret from redis: v1 with 207 millis Get ret from redis: v1 with 215 millis Get ret from redis: v1 with 223 millis Get ret from redis: v1 with 291 millis Get ret from redis: v1 with 220 millis Get ret from redis: v1 with 214 millis Get ret from redis: v1 with 219 millis Get ret from redis: v1 with 257 millis Get ret from redis: v1 with 214 millis Get ret from redis: v1 with 211 millis Process finished with exit code 0
能夠看出,第一次500多毫秒,以後都是200多毫秒,速度有提升。oop