I'm looking for best way to check connection to Mongo DB. Situation: client makes request (api) to server. And server returns status of all databases.

What the best way to do it?

Solution 1

I use this:

Builder o = MongoClientOptions.builder().connectTimeout(3000);  
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3001), o.build());    

try {
  mongo.getAddress();
} catch (Exception e) {
  System.out.println("Mongo is down");
  mongo.close();
  return;
}

Solution 2

In Java MongoDriver 3.3.0 use ServerMonitorListener to determine whether server is up and connected or not. Here is the example code,

public class ServerConnection implements ServerMonitorListener {
    private MongoClient client;

    public ServerConnection(){
        try {
            MongoClientOptions clientOptions = new MongoClientOptions.Builder()
                .addServerMonitorListener(this)
                .build();

            client = new MongoClient(new ServerAddress("localhost", 27017), clientOptions);
        } catch (Exception ex) {

        }
    }

    @Override
    public void serverHearbeatStarted(ServerHeartbeatStartedEvent serverHeartbeatStartedEvent) {
        // Ping Started
    }

    @Override
    public void serverHeartbeatSucceeded(ServerHeartbeatSucceededEvent serverHeartbeatSucceededEvent) {
        // Ping Succeed, Connected to server
    }

    @Override
    public void serverHeartbeatFailed(ServerHeartbeatFailedEvent serverHeartbeatFailedEvent) {
        // Ping failed, server down or connection lost
    }
}

Solution 3

The ping command is a no-op used to test whether a server is responding to commands. This command will return immediately even if the server is write-locked:

        try{

            DBObject ping = new BasicDBObject("ping", "1");
            mongoTemplate.getDb().getMongo().getDB("DATABASE NAME"").command(ping);
        } catch (Exception exp){
            // MongoDb is down..
        }

Solution 4

Use MongoClient for Java, all the info you need is here...

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

Solution 5

If I understand your question correctly you want to get state returned via a web service call. You can write a function that invokes db.serverStatus() and have it return the data. Check out the documentation here:

Monitoring for MongoDB