I'm using Jedis pool to manage connections to Redis server. An example code of mine as follows:
public Set<String> getTopArticleList(int start, int end) { Set<String> list = null; Jedis j = JedisFactory.getInstance().getJedisPool().getResource(); Pipeline pipe = j.pipelined(); try { // do stuff with redis pipe.sync(); } catch (JedisConnectionException jex) { JedisFactory.getInstance().getJedisPool().returnBrokenResource(j); } finally { JedisFactory.getInstance().getJedisPool().returnResource(j); } return list; }
Code to create and retrieve the Jedis pool:
class JedisFactory { private static JedisPool jedisPool; public JedisFactory() { JedisPoolConfig poolConfig = new JedisPoolConfig(); jedisPool = new JedisPool( poolConfig, RedisDBConfig.HOST, RedisDBConfig.PORT, RedisDBConfig.TIMEOUT, RedisDBConfig.PASSWORD ); } public JedisPool getJedisPool() { return jedisPool; } public static JedisFactory getInstance() { if (instance == null) { instance = new JedisFactory(); } return instance; } }
The problem is that after reaching the number of limited connections, the web cannot be accessed anymore. Am I doing something wrong?
Jedis is not thread safe (should add that to the documentation). You can either use one Jedis per thread or JedisPool, which is a thread safe pool of jedis. I would recommend JedisPool for most cases since it will reuse Jedis instances, resulting in better performance.
Overview. This article is an introduction to Jedis, a client library in Java for Redis – the popular in-memory data structure store that can persist on disk as well. It is driven by a keystore-based data structure to persist data and can be used as a database, cache, message broker, etc.
To improve performance, go-redis automatically manages a pool of network connections (sockets). By default, the pool size is 10 connections per every available CPU as reported by runtime.
You haven't configured the maxTotal size of the pool, and the default value is only 8. You could change the JedisFactory constructor to:
public JedisFactory() { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(128); jedisPool = new JedisPool(poolConfig, RedisDBConfig.HOST, RedisDBConfig.PORT, RedisDBConfig.TIMEOUT, RedisDBConfig.PASSWORD); }
Beware also of the default value of the WhenExhaustedAction (WHEN_EXHAUSTED_BLOCK), as it may not be your desired behavior.
Jedis uses Apache Commons Pool, and you can read about it's parameters here: GenericObjectPool
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With