6

I am using the Redis in Java using the Jedis client. I am creating a JedisPool and would like to know if the connection is successful, is there a way of doing this without fetching an object?

user2248702
  • 2,741
  • 7
  • 41
  • 69

2 Answers2

10

You can attempt to get the Jedis resource from the JedisPool. A JedisConnectionException will be thrown if a connection has not been established:

JedisPool pool = new JedisPool(...);
try {
    Jedis jedis = pool.getResource();
    // Is connected
} catch (JedisConnectionException e) {
    // Not connected
}
August
  • 12,410
  • 3
  • 35
  • 51
2

I have deployed a new method witch uses "ping" function from Jedis. This requires a new JedisPool independent for this purpose:

/**
 * 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;

}

INFO: You can see the full class at this place: https://github.com/mami-project/KeyServer/blob/master/src/main/java/es/tid/keyserver/controllers/db/DataBase.java