3

My application interacts with two databases: one on MongoDB and the other one on Neo4J.

The problem is that if the databases are disabled or unreachable the app crashes. I resolve the issue about Neo4J thanks to the method verifyConnectivity of Neo4J driver and with a try-catch statement, but with MongoDB the problem remains. In fact it seems that the app waits for MongoDB but MongoDB is disabled and so the app waits for an infinite time without sending any exception.

I am looking for a way to understand that MongoDB is unreachable in order to notify this to the user, maybe a timeout or something like this is needed? In this case how can I set it?

The programming language that I am using is Java and the MongoDB driver version is the following:

    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.1.1</version>

EDIT:

try
{
    mongoClient = MongoClients.create(connectionString);
    database = mongoClient.getDatabase(dbName);
    DBObject ping = new BasicDBObject("ping","1");
    database.runCommand((Bson) ping);
}
catch (Exception ex)
{
    System.err.println("MongoDB is not available");
    return false;
}
return true;

1 Answer 1

1

You can test it with ping (see here), which is a no-op.

try
{
  DBObject ping = new BasicDBObject("ping", "1");
  mongoClient.getDb().getMongo().getDB("<YOUR_DB").command(ping);
} catch (Exception exp){
  //Cannot connect to MongoDB or your DB
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you I adapt your solution to my code. I post it in the question as EDIT
Anyway, I have to wait for some time before the exception is issued. For the application purpose is not a critical issue but I would like to reduce the timeout in order to have a small wait for the user. I found a old question but it doesn't work with java. link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.