Jedis - When to use returnBrokenResource()

北慕城南 提交于 2021-02-18 10:20:11

问题


When exactly we should use this method. On JedisConnectionException, JedisDataException or for any JedisException. There is no good API documentation for Jedis to my knowledge.

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);
}

回答1:


You are supposed to use returnBrokenResource when the state of the object is unrecoverable. A Jedis object represents a connection to Redis. It becomes unusable when the physical connection is broken, or when the synchronization between the client and server is lost.

With Jedis, these errors are represented by the JedisConnectionException. So I would use returnBrokenResource for this exception, and not the other ones.

JedisDataException is more related to bad usage of the Jedis API, or to server-side Redis errors.

JedisException is for everything else (usually raised after a lower-level error, independant from Jedis).




回答2:


For latecomers!

returnBrokenResource(), returnResource() are deprecated. Just use jedis.close() in finally block safely.

finally {
  if (jedis != null) {
    jedis.close();
  }
}

If Jedis was borrowed from pool, it will be returned to pool with proper method since it already determines there was JedisConnectionException occurred. If Jedis wasn't borrowed from pool, it will be disconnected and closed.




回答3:


sample code for this as per jedis documentation

public String get(String keyName)
{
    Jedis redis = null;
    try
    {
        redis = redisPool.getResource();
        return redis.get(keyName);
    }
    catch (JedisConnectionException e) 
    {
        if (redis != null) 
        {
            redisPool.returnBrokenResource(redis);
            redis = null;
        }
        throw e;
    }
    finally
    {
        if (redis != null)
        {
            redisPool.returnResource(redis);
        }
    }
}


来源:https://stackoverflow.com/questions/17082163/jedis-when-to-use-returnbrokenresource

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