Is there a way to verify that mongodb is running in Java?

226 views Asked by At

Currently my application uses MongoDB. If I send a request while mongo is not running it will wait 30 seconds before returning a Timeout Error. Is there a way that I can catch this while starting up my application?

2

There are 2 answers

0
bcgilmartin On BEST ANSWER

Ended up going with pinging the Socket:

public static void mongoIsConnected() throws Exception {
    String mongoUrlStr = "http://localhost:27017"; // mongo url
    URL mongoURL = new URL(mongoUrlStr);
    SocketAddress socketAddress = new InetSocketAddress(mongoURL.getHost(), mongoURL.getPort());
    Socket socket = new Socket();
    socket.connect(socketAddress, 1000);
}

This will throw an error if mongo is not connected

0
D. SM On

You can:

  • Reduce the server selection timeout. See here for relevant development and production configuration guidance.
  • Create another client with a low server selection timeout (e.g. 1) and perform a ping (issue {ping:1} using run command helper). This way you'll know within 1 second whether the deployment is up & running.