Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check connection Redis

Tags:

java

redis

jedis

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?

like image 415
user2248702 Avatar asked Aug 11 '14 05:08

user2248702


Video Answer


2 Answers

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
}
like image 193
August Avatar answered Oct 02 '22 07:10

August


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

like image 21
Javier Martinez Gusano Avatar answered Oct 02 '22 06:10

Javier Martinez Gusano