简体   繁体   中英

How do I check MongoDB 3.0 Client Connection Status with the Java Driver?

I am having problems because I only want my code to execute after the MongoClient has successfully made a connection. But I am having problems finding documentation on this. Here is my example

MongoClientURI connectionString = new MongoClientURI("mongodb://"+mongoUser+":"+mongoPassword+"@"+config.getMongodbHost()+":"+config.getMongodbPort()+"/"+config.getMongodbDatabase());
        mongoClient = new MongoClient(connectionString);
        goldfishDatabase = mongoClient.getDatabase("goldfish");

System.out.println("Don't print this line until the connection has been made.");

The driver maintains a connection pool. So a general problem should make

mongoClient = new MongoClient( connectionString )

throw an exception, a MongoException, specifically. After that, if a connection is needed, the driver provides a connection.

Let's assume the database gets down at some point after the call to new MongoClient() . Then, the operation which needs a connection would fail, in case of write operations with a MongoWriteException . Read operations will fail with a MongoSocketReadException , or with a MongoReadTimeoutException . Have a detailed look in the MongoException API docs .

Note that these are all Runtime exceptions, and hence are unchecked aren't enforced to be caught. However, runtime exceptions can be caught like any other exception

try {
  mongoClient = new MongoClient( connectionString )
} catch (MongoException me) {
  // handle exception
}

So unless an exception is thrown, assume everything to be in a consistent state - which is the Java way.

In JavaScript, you can just print out the error.

    try{
        mongoose.connection('connetion url');
    }catch(error){
        console.log(error);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM