[英]How to create several Jedis instances using JedisPool in a multithreaded environment
我試圖使用JedisPool創建多個Jedis實例以用於多線程(每個線程可以有一個Jedis實例)。 但是,當我嘗試使用JedisPool.getResource()創建多個實例時,它總是為我提供相同的Jedis實例。 以下代碼也將給我redis.clients.jedis.exceptions.JedisConnectionException: Unexpected end of stream
由於多個線程的單個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
類中的每個操作期間,從池中獲取Jedis
對象並使用它。 例如:
class MyThread {
void doSomething() {
try (Jedis jedis = jedisPool.getResource()) {
jedis.exists(key);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.