检查连接Redis

时间:2014-08-11 05:11:52

标签: java redis jedis

我使用Jedis客户端在Java中使用Redis。我正在创建一个JedisPool并且想知道连接是否成功,有没有办法在不获取对象的情况下执行此操作?

2 个答案:

答案 0 :(得分:4)

您可以尝试从Jedis获取JedisPool资源。如果尚未建立连接,则会抛出JedisConnectionException

JedisPool pool = new JedisPool(...);
try {
    Jedis jedis = pool.getResource();
    // Is connected
} catch (JedisConnectionException e) {
    // Not connected
}

答案 1 :(得分:0)

我已经部署了一个使用Jedis的“ping”功能的新方法。这需要一个独立的新JedisPool用于此目的:

/**
 * Check if the current data base object is connected to the Redis Data Base.
 * @return True if is connected, false if not.
 * @since v0.3.0
 */
public boolean isConnected(){
    try{
        monitorDbObj.ping();
        return true;
    } catch (JedisConnectionException e){ 
        if(!this.connecting){
            connecting = true;  // Set the connecting flag True (trying to connect...).
            try{
                isConnected = connectDb();
            } catch (JedisConnectionException ex){
                isConnected = false;
            } 
            connecting = false; // Set the connecting flag to False (connected).
        } 
    } catch (JedisDataException e){
        LOGGER.info("Redis is busy loading the data set in memory.");
        connecting = false;
    }
    return false;

}

信息:您可以在此处看到完整的课程:https://github.com/mami-project/KeyServer/blob/master/src/main/java/es/tid/keyserver/controllers/db/DataBase.java