how to check from a driver, if mongoDB server is running

Viewed 25227

I wonder, if there is a way to check if mongoDB server is running from java driver for mongoDB?

According to the tutorial, I can do

Mongo m = new Mongo();
// or
Mongo m = new Mongo( "localhost" , 27017 );
// and
DB db = m.getDB( "mydb" );

But how to check that I can use these Mongo and DB? I see no isConnected() method in the API.

db.getConnector().isOpen() 

returns true

The only way I found is call db.getDatabaseNames() and catch MongoException.

If there some more civilized approach?

5 Answers
public boolean keepAlive(Mongo mongo) {
    return mongo.getAddress() != null;
}

This will return null for address if mongo is down. You can look within the implementation of getAddress() to see why it is a good way to check the mongo's status.

I assume you've initialized the mongo parameter properly.

I haven't tested this thoroughly (only using a localhost mongo) but it appears to work so far:

public boolean mongoRunningAt(String uri) {
    try {
        Mongo mongo = new Mongo(new MongoURI(uri));
        try {
            Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
            socket.connect(mongo.getAddress().getSocketAddress());
            socket.close();
        } catch (IOException ex) {
            return false;
        }
        mongo.close();
        return true;
    } catch (UnknownHostException e) {
        return false;
    }
}

And the tests I've used:

@Test
public void whenMongoNotAvailableAtSpecificURLThenTheLoaderKnows() {
    assertThat(mongoRunningAt("mongodb://127.0.0.1:12345"), is(false));
}

@Test
public void whenMongoAvailableAtSpecificURLThenTheLoaderKnows() {
    assertThat(mongoRunningAt("mongodb://127.0.0.1:27017"), is(true));
}

It's not exactly using a well defined public API so use at your own risk.

Related