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?
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 } 2 Comments
user2248702
Do you need to return the resource to the pool? If so, how would you go about doing it as you have created it in the try block?
August
You should return the resource when you're done using that instance.
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