Jedis Pool如何运作?

时间:2014-01-20 09:37:10

标签: java connection-pooling jedis

我正在使用Jedis池来管理与Redis服务器的连接。我的示例代码如下:

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;
}

创建和检索Jedis池的代码:

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;
    }
 }            

问题是在达到有限连接数后,无法再访问该网页。我做错了吗?

1 个答案:

答案 0 :(得分:35)

您尚未配置池的 maxTotal 大小,默认值仅为8.您可以将JedisFactory构造函数更改为:


    public JedisFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(128);
        jedisPool = new JedisPool(poolConfig, RedisDBConfig.HOST, RedisDBConfig.PORT, RedisDBConfig.TIMEOUT, RedisDBConfig.PASSWORD);
    }

还要注意 WhenExhaustedAction (WHEN_EXHAUSTED_BLOCK)的默认值,因为它可能不是您想要的行为。

Jedis使用Apache Commons Pool,你可以在这里阅读它的参数:GenericObjectPool