redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool

使用redis链接池,每隔一段时间就报错java

redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool  
    at redis.clients.util.Pool.getResource(Pool.java:22)  
    at com.derbysoft.jredis.longkeytest.BorrowObject.run(BorrowObject.java:22)  
    at java.lang.Thread.run(Thread.java:662)  
Caused by: java.util.NoSuchElementException: Timeout waiting for idle object  
    at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1134)  
    at redis.clients.util.Pool.getResource(Pool.java:20)

缘由是没有回收资源致使
正确的作法是redis

ShardedJedis jedis = shardedJedisPool.getResource();
try {
    jedis.set(key, value);
} finally {
    shardedJedisPool.returnResource(jedis);
}

若是你用的jedis 2.4.2以及之前版本,用完以后别忘了return链接到资源池。apache

不过2.5.0版本以后,jedis使用了try-with-resource,jedis用完了就会自动归还了,不用每次都本身return了。网络

各类连接数的参数本身调一下。例如MaxTotal,MaxIdle等等~socket

若是redis server不在局域网内,可能会由于network问题致使连接超时,会抛出socket的异常,固然写数据就也会丢失。code

connection的timeout默认是2000ms,你能够本身调的大一些,这样网络慢的时候就不至于丢失数据。server

相关文章
相关标签/搜索