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)
原因是没有回收资源导致
正确的做法是
更新内容:
如果你用的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.