redis运用连接池报错解决

redis使用连接池报错解决
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,你可以自己调的大一些,这样网络慢的时候就不至于丢失数据。

十分重要的一点:在开发的时候,方法A调用方法B,方法A需要获取jedis 链接,方法B也要获取jedis链接,在实现的时候尽量让他们公用连接,例如B用A的链接,这样效率会快非常多,而且也不会浪费链接。

最重要的一点,从google老外回答:

1.I test it using a multi-thread code, when the poolSize > maxclients(redis.conf),
it will throw this exception. And it runs well when the maxclients is larger than poolSize.


2.If you set maxclients to 10, and set fixed thread pool size to 20, it prints ".. fail to get connection...".
If you set maxclients to 10, and set fixed thread pool size to 5, it runs well.

 

从而得之,在redis配置文件,redis.conf文件中,有个参数设置,maxclients(默认是注释掉的,不设置此值时表示无redis客户端连接个数限制)。

设置时,maxclients的值要大于poolSize(最大连接池的链接个数)。

 

posted @ 2014-11-05 14:24  GisClub  阅读(24446)  评论(0编辑  收藏  举报