绝地武士池如何运作?

2022-09-01 05:22:58

我正在使用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;
    }
 }            

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


答案 1

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


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

还要注意“当用尽”操作(WHEN_EXHAUSTED_BLOCK)的默认值,因为它可能不是您想要的行为。

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


答案 2

推荐