Wednesday 12 October 2011

Detecting if Mongo is running in your app (by K)

We use MongoDB for a load of stuff.
One thing that is a problem is that, in the dev environment, the mongo service needs to be restarted.
(In production we have different mechanisms of course)
So for a period of time while developing an app, Mongo may not be running.
And if you make any call to it in your app you get a shed load of exceptions that, for some reason, can't be caught.

This kind of thing:

[#|2011-10-11T17:44:58.420+1000|WARNING|glassfish3.1.1|com.mongodb.tcp|_ThreadID=27;_ThreadName=Thread-3;|Exception determining maxBSON size using0 couldn't connect to [] Connection refused
at com.mongodb.DBPort._open(
at com.mongodb.DBPort.go(
at com.mongodb.DBPort.go(
at com.mongodb.DBPort.findOne(
at com.mongodb.DBPort.runCommand(
at com.mongodb.DBTCPConnector.fetchMaxBsonObjectSize(
at com.mongodb.DBTCPConnector.checkMaster(
at com.mongodb.DBApiLayer$MyCollection.__find(
at com.mongodb.DBCollection.findOne(
at com.mongodb.DBCollection.findOne(

So I did some digging to find out what's going on and how to programmatically checking if the service is available.
I found this:

And made my own version which is called before any persistent action.
Here are the bones of it so you can modify it to suit your needs.

boolean mongoRunning = false;
ServerAddress serverAddress = new ServerAddress(dbHost);  // dbHost is the mongo host name
DBPortPool pool = mongo.getConnector().getDBPortPool(serverAddress); // mongo is the instance
DBPort port = pool.get();
try {
  mongoRunning = true;
} catch (IOException e) {
  // Uh oh. Mongo not running. Do something meaningful...
  log.error("MongoDB isn't running on [" + dbHost + "][" + dbPort + "]"); // or just log it
} finally {
  port.close(); // should do try/catch here...

It's overkill of course, but it does help.
Just to help out.

No comments:

Post a Comment