如何在多线程环境中使用 JedisPool 创建多个 Jedis 实例

How to create several Jedis instances using JedisPool in a multithreaded environment

我尝试使用 JedisPool 创建多个 Jedis 实例以供多线程使用(每个线程可以有一个 Jedis 实例)。但是当我尝试使用 JedisPool.getResource() 创建多个实例时,它总是给我相同的 Jedis 实例。由于多个线程的单个 Jedis 实例,下面的代码也会给我 redis.clients.jedis.exceptions.JedisConnectionException: Unexpected end of stream

private final static JedisPoolConfig poolConfig = buildPoolConfig();
private static JedisPool jedisPool = new JedisPool(poolConfig, "localhost");

public static void main(String[] args) throws Exception {
    MyThread[] myThreads = new MyThread[4];
    for (int i = 0; i < myThreads.length; i++) {
       try (Jedis jedis = jedisPool.getResource()) {
           System.out.println("jedis " + i  + ": "+ jedis);
           myThreads[i] = new MyThread(jedis);
           myThreads[i].start();
       }
    }
    jedisPool.close();
}

private static JedisPoolConfig buildPoolConfig() {
    final JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxTotal(128);
    poolConfig.setMaxIdle(128);
    poolConfig.setMinIdle(16);
    poolConfig.setTestOnBorrow(true);
    poolConfig.setTestOnReturn(true);
    poolConfig.setTestWhileIdle(true);
    poolConfig.setMinEvictableIdleTimeMillis(Duration.ofSeconds(60).toMillis());
    poolConfig.setTimeBetweenEvictionRunsMillis(Duration.ofSeconds(30).toMillis());
    poolConfig.setNumTestsPerEvictionRun(3);
    poolConfig.setBlockWhenExhausted(true);
    return poolConfig;
}

任何帮助将不胜感激。谢谢!

您应该在多线程环境中使用 JedisPool。但是,根据您的实施,您实际上是在那种情况下使用 Jedis

要解决这个问题,您可以使用 JedisPool 而不是 Jedis 作为 MyThread 构造函数。

public static void main(String[] args) throws Exception {
    MyThread[] myThreads = new MyThread[4];
    for (int i = 0; i < myThreads.length; i++) {
        myThreads[i] = new MyThread(jedisPool);
        myThreads[i].start();
    }
    jedisPool.close();
}

MyThread class 的每个操作中,从池中取出一个 Jedis 对象并使用它。例如:

class MyThread {
    void doSomething() {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.exists(key);
        }
    }
}