简体   繁体   English

如何使用Java驱动程序检查MongoDB 3.0客户端连接状态?

[英]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. 我遇到问题是因为我只希望我的代码在MongoClient成功建立连接后才能执行。 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. 抛出一个异常,特别是MongoException。 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() . 假设在调用new MongoClient()之后数据库在某个时刻new MongoClient() Then, the operation which needs a connection would fail, in case of write operations with a MongoWriteException . 然后,在使用MongoWriteException进行写操作的情况下,需要连接的操作将失败。 Read operations will fail with a MongoSocketReadException , or with a MongoReadTimeoutException . 读取操作将因MongoSocketReadExceptionMongoReadTimeoutException而失败 Have a detailed look in the MongoException API docs . 详细了解MongoException API文档

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. 因此,除非引发异常,否则假设一切都处于一致状态-这是Java的方式。

In JavaScript, you can just print out the error. 在JavaScript中,您可以仅打印出错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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