在使用 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
}
这对我有用! 根据我的发现,我尝试过并且可以为其他人派上用场的事情:
当(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服务器是否在线。为了防止耗尽,请始终 close() 从 JedisPool 收集的 jedis 实例。
还要检查您是否需要超过 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();
}
}
}