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?
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
}
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With