如何检查是否与Java建立了MongoDB连接?

时间:2016-04-10 09:21:16

标签: java mongodb exception-handling mongo-java mongo-java-driver

在我的应用程序中,MongoDB 3.2.4在自定义端口上运行,我想实现逻辑,我的应用程序将尝试在自定义端口上访问MongoDB,如果失败,它将使用默认的27018端口。

为此,我使用以下代码:

String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT_CUS + "/" + dbName;
MongoClientURI connectionString = new MongoClientURI(mongoClientURI);

// enable SSL connection
MongoClientOptions.builder().sslEnabled(true).build();

if (this.mongoClient == null) {
    this.mongoClient = new MongoClient(connectionString);
}

// create database if doesn't exist
MongoDatabase mdb = this.mongoClient.getDatabase(dbName);

try {
    this.mongoClient.getAddress();
} catch (com.mongodb.MongoSocketOpenException e) {
    System.out.println("Switch to default port");
    /*…use default port logic…*/
}

问题是没有捕获到此异常。 虽然MongoDB抛出以下异常:

  

com.mongodb.MongoSocketOpenException:异常打开套接字at   com.mongodb.connection.SocketStream.open(SocketStream.java:63)at   com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)     在   com.mongodb.connection.DefaultServerMonitor $ ServerMonitorRunnable.run(DefaultServerMonitor.java:128)     在java.lang.Thread.run(Thread.java:745)引起:   java.net.ConnectException:拒绝连接:connect at   java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)at   java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)     在   java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)     在   java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)     在   java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)     在java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)at   java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)at   java.net.Socket.connect(Socket.java:589)at   com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)     在com.mongodb.connection.SocketStream.open(SocketStream.java:58)     ......还有3个

我的try-catch表达式无法捕获此异常。

我尝试了多种方法,例如捕获:

  • Exception
  • RuntimeException
  • MongoSocketOpenException
  • MongoException
  • MongoCommandException

它们都不起作用。

我的问题:

  1. 如何检查MongoDB连接是否已建立?
  2. 如何捕获异常MongoSocketOpenException

0 个答案:

没有答案