如何在创建MongoClient实例

时间:2016-11-25 22:41:50

标签: mongodb mongodb-java

我使用Mongo DB java驱动程序连接到mongo实例。下面是我用来创建MongoClient实例的代码。

try {
            new MongoClient("localhost", 1111);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

如果主机名或端口号不正确,我将获得以下异常。我想我怎么能抓住这些例外。 MongoDB连接发生在内部线程中,客户端代码无法捕获它。我想知道MongoClient是否已正确连接。我怎样才能获得这些信息?

INFO: Exception in monitor thread while connecting to server localhost:0
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Can't assign requested address (connect failed)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    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)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more

EDIT1

我的代码无法捕获上面显示的异常。它可能是由Mongo代码捕获的。所以我不知道实例是否正确创建。

4 个答案:

答案 0 :(得分:2)

在守护程序线程上创建服务器连接。总而言之,您在创建Mongo客户端时无法检查与连接相关的错误。

当您创建第一个涉及读取或写入的真实数据库时,您必须延迟连接检查。

只是出于演示目的而让您有所了解。

MongoClient mongoClient = new MongoClient("127.0.34.1", 89);
DB db = mongoClient.getDB("test");
try {
   db.addUser("user", new char[] {'p', 'a', 's', 's'});
} catch(Exception e) { MongoTimeoutException exception}
来自Deamon Thread的

MongoSocketOpenException

INFO: Exception in monitor thread while connecting to server 127.0.34.1:89
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect

主线程中的MongoTimeoutException

Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=127.0.34.1:89, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, 
caused by {java.net.ConnectException: Connection refused: connect}}]
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:375)

所以使用MongoTimeoutException将代码包装在try catch块中,它可以用于检查与连接相关的错误。

答案 1 :(得分:1)

它非常简单和优雅:

  1. System.err重定向到文件:

    ByteArrayOutputStream file=new ByteArrayOutputStream();
    System.setErr(new PrintStream(file));
    
  2. 使用MongoClientMongoCredentials

    连接到服务器
    MongoCredential credenciales=MongoCredential.createCredential("root", "admin", "root".toCharArray());
    MongoClient client = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credenciales));
    
  3. 读取错误输出,该输出位于ByteArrayOutputStream对象中:

    String texto=new String(file.toByteArray());
    
  4. 检查Autentication failed字符串是否存在:

    if (texto.contains("'Authentication failed.'"))
       // do something;
    else
      ...
    

答案 2 :(得分:0)

对于现在偶然发现此问题的任何人。我遇到了同样的问题,并尝试使用Macario的答案,但运气不佳。然后意识到,监视连接的线程不是将其发送到System.err,而是将其发送到System.out,因此可以像这样使用System.out而不是使用System.err:

PrintStream out = System.out;  // Save the original out stream to reset later

// Set out to a buffer
ByteArrayOutputStream file=new ByteArrayOutputStream();
System.setOut(new PrintStream(file));

mongoClient = new MongoClient(new MongoClientURI("<connection_string>")));

// Found this to be important as we need to wait for the thread to dump to out
// 1000 millis was too fast for me but 2000 did the trick
Thread.sleep(2000);

// Convert buffer to a string
String texto=new String(file.toByteArray());

System.setOut(out); // Reset out

// Check if saved out contins the error (I was looking for MongoSocketException)
if(texto.contains("MongoSocketException")){
    // Do Stuff
}

答案 3 :(得分:-5)

  new MongoClient("localhost", 1111);

        } catch (MongoSocketOpenException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

您只需在catch块中命名相应的异常即可。这适用于任何例外。您可以为每个唯一的异常添加尽可能多的catch块