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

╄→гoц情女王★ 提交于 2020-04-11 16:36:56

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

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)

原因是没有回收资源导致
正确的做法是

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

如果你用的jedis 2.4.2以及以前版本,用完之后别忘了return连接到资源池。

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

各种链接数的参数自己调一下。例如MaxTotal,MaxIdle等等~

如果redis server不在局域网内,可能会因为network问题导致链接超时,会抛出socket的异常,当然写数据就也会丢失。

connection的timeout默认是2000ms,你可以自己调的大一些,这样网络慢的时候就不至于丢失数据。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!