JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
因为JedisPool是线程安全的, 因此我们可以将它缓存起来, 供所有线程使用.
JedisPoolConfig包含了一个丰富有用的Redis连接配置参数. JedisPoolConfig基于Commons Pool 2
1 2 3 4 5 6 7 8 9 10
/// Jedis implements Closable. Hence, the jedis instance will be auto-closed after the last statement. try (Jedis jedis = pool.getResource()) { /// ... do stuff here ... for example jedis.set("foo", "bar"); String foobar = jedis.get("foo"); jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); Set<String> sose = jedis.zrange("sose", 0, -1); } /// ... when closing your application: pool.destroy();
Jedis jedis = null; try { jedis = pool.getResource(); /// ... do stuff here ... for example jedis.set("foo", "bar"); String foobar = jedis.get("foo"); jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); Set<String> sose = jedis.zrange("sose", 0, -1); } finally { if (jedis != null) { jedis.close(); } } /// ... when closing your application: pool.destroy();
If Jedis was borrowed from pool, it will be returned to pool with proper method since it already determines there was JedisConnectionException occurred. If Jedis wasn’t borrowed from pool, it will be disconnected and closed.