【问题标题】:Is there a way to have Jedis automatically use a connection pool for command methods?有没有办法让 Jedis 自动为命令方法使用连接池?
【发布时间】:2021-08-27 17:56:38
【问题描述】:

我在一个项目中遇到了一个看起来像这样的课程

public class RedisClient {
    Logger logger = LoggerFactory.getLogger(RedisClient.class);
    JedisPool pool;
    public RedisClient(String redisHost, int redisPort, String redisPassword) {
        JedisPoolConfig poolConfig = buildPoolConfig();
        try {
            pool = new JedisPool(poolConfig, redisHost, redisPort, 10000, redisPassword, true);
        } catch (Exception e) {
            logger.error("There's been an error while Jedis attempted to retrieve a thread from the pool", e);
        }
    }
    public void set(String key, String value) {
        try (Jedis jedis = pool.getResource()) {
            jedis.set(key, value);
        }
    }
   // ... a few more command methods wrapped with try (Jedis jedis = pool.getResource())
   // like get, expire, etc.

虽然这无论如何都不是一个坏方法(在我看来这是相当标准的适配器模式),但我想知道 Jedis 是否会自动处理这个问题(来自 Python,我希望它可能隐藏了这个细节la redis,或者还有另一种方法可以将现有客户端配置为“为每个命令使用连接池”。我看到 jedis.Jedis 有一个接受 JedisPoolsetDataSource 方法,但我有很难确定它实际上做了什么以及它是否有助于我回答我的问题。

【问题讨论】:

    标签: java redis jedis


    【解决方案1】:

    JedisPool 在commons-pool2 之上实现。根据 commons-pool2 的设计,你可以借用一个对象,但你必须在使用后归还该对象。 Jedis 在这个返回过程中加入了close 方法,借助Java 的try-with-resources 特性来简化用户的工作。借用过程中使用setDataSource方法,类似于归还过程中使用的close方法。

    最后但同样重要的是,用户不得使用setDataSource 方法;除非她/他正在实施她自己的 JedisPool 版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多