Jedis - 何时使用returnBrokenResource()

use*_*253 11 java exception redis jedis

什么时候我们应该使用这种方法.在JedisConnectionException,JedisDataException或任何JedisException上.据我所知,Jedis没有好的API文档.

try {
    Jedis jedis = JedisFactory.getInstance();
    Pipeline pipe = jedis.pipelined();
    Response<Set<Tuple>> idWithScore = pipe.zrangeWithScores(cachekey, from, to);
    **// some statement which may cause some other exception**
    Response<String> val = pipe.get(somekey);
    pipe.exec();
    pipe.sync();
}catch (JedisConnectionException e) {
    JedisFactory.returnBrokenResource(jedis);
}catch(Exception e){
    **// What API I should use here?, how to find whether to use returnBrokenResource(jedis) or returnResource(jedis)**
}finally{
    JedisFactory.returnResource(jedis);
}
Run Code Online (Sandbox Code Playgroud)

小智 11

对于后来者!

不推荐使用returnBrokenResource(),returnResource().只需在finally块中安全地使用jedis.close().

finally {
  if (jedis != null) {
    jedis.close();
  }
}
Run Code Online (Sandbox Code Playgroud)

如果从池中借用Jedis,它将以适当的方法返回池,因为它已经确定发生了JedisConnectionException.如果Jedis没有从池中借来,它将被断开并关闭.

  • 你在哪里找到这方面的文档? (2认同)

Did*_*zia 10

当对象的状态不可恢复时,您应该使用returnBrokenResource.Jedis对象表示与Redis的连接.当物理连接中断或客户端与服务器之间的同步丢失时,它将变得不可用.

使用Jedis,这些错误由JedisConnectionException表示.所以我会将returnBrokenResource用于此异常,而不是其他异常.

JedisDataException与Jedis API的错误使用或服务器端Redis错误更相关.

JedisException用于其他所有内容(通常在较低级别的错误之后引发,与Jedis无关).

  • 让我说我抓住了JedisConnectionException和returnBrokenResource.我还应该在finally块中返回returnResource吗?它会导致两次返回资源有什么问题吗? (6认同)
  • Jedis池使用apache通用GenericObjectPool实现.对象不得两次返回池中.见http://commons.apache.org/proper/commons-pool/api-1.6/org/apache/commons/pool/impl/GenericObjectPool.html#returnObject(T) (2认同)