簡體   English   中英

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)

[英]redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)

在使用 Jedis 訪問 Redis 時嘗試使用 Jedis.get(key) 時出現此錯誤。

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)

訪問 Redis 的代碼如下所示:

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

this.jedisPool = new JedisPool(poolConfig, "localhost", 6379, 4000);
this.jedis = jedisPool.getResource();


//Now using this jedis connection to retrieve values for key
jedis.get(key)  // error occurs

解決方案是創建 Jedis 實例,如下所示:

 try (Jedis jedis = jedisPool.getResource()) { 
     // do get here
  }

這對我有用! 根據我的發現,我嘗試過並且可以對其他人派上用場的東西:

  1. 嘗試更改 Redis jar 版本。
  2. 檢查日志,如果您看到一些與保護模式相關的錯誤,您可能需要將其關閉。
  3. 檢查您的 Redis 集群/實例是否已啟動並正在運行。

當 (JedisPool) 資源耗盡時,可能會發生這種錯誤。

嘗試包裝在 try-catch-finally 塊中,並在 finally 塊中將 jedis 資源返回到池中。

說明相關塊的示例:

try {
  
  jedis = jedisPool.getResource();
  String value = jedis.get(key);
  //do something with value

} catch (Throwable e) {

  //handle exception

} finally {
  
  if (jedis != null) {
    //free the jedis resource
    jedisPool.returnResource(jedis);
  }

}

檢查你的 Redis 服務器是否在線。 並且為了防止耗盡,請始終關閉()您從 JedisPool 收集的絕地實例。

還要檢查您是否需要超過 200 個(默認最大總連接數)

    try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(1000); // set max here
            jedisPool = new JedisPool(config, redisHost, redisPort, 10000);     
        }catch(Exception e){
            System.out.println("have error while creating jedisPool " + e);
        }

當你使用 jedis 時,按如下方式使用:

func(){
       Jedis userTemplate = null;
        try {
            jedis = jedisPool.getResource();
            // do stuff here
            // jedis.get("hi-there");
        }catch(Exception e) {
            System.out.println("error in getting resource " + e);
        }finally {
            if(userTemplate != null) {
                userTemplate.close();
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM