user3019299
user3019299

Reputation: 199

Java mongodb Re-connection

When I write a java program which connects to mongodb, I cannot find any java api which check the mongodb connection status, like "isConnected" method. I use the following code to set up the connection:

Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("database");
DBCollection col = db.getCollection("collection");

But what if it cannot establish the connection (e.g. mongodb service is not running), and I want to re-connect to mongodb until the connection is available?

while(mongo == null)
{
   //connect to mongo again
}

I am not sure the above code is correct or not because actually it doesn't check the connection status. So is there any other way to do the re-connection?

Upvotes: 0

Views: 1052

Answers (2)

evanchooly
evanchooly

Reputation: 6233

You can do a check to see if it's connected and maybe it would be at that moment. But what if it goes down between your check and your actual operation? You'll still need to handle connection failures then anyway. Checking a "isConnected()" is a feel good solution that doesn't really offer any benefits. Your best bet is to just try your work. If there's a connection failure, the java driver will try to reconnect (the server or network might be down...) and then you can retry.

Upvotes: 2

peter.petrov
peter.petrov

Reputation: 39457

Not sure but I think you might be using an old Java MongoDB client/driver.
In newest clients/drivers the class is called MongoClient.

http://api.mongodb.org/java/current/

You can instantiate it and call getDatabaseNames() or getDB( "admin" )

If that call succeeds (does not throw an exception), then
the server is up and you're connected. Otherwise, there's
a problem.

See also:

http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

Upvotes: 0

Related Questions