繁体   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