无法从java连接到本地monogoDB [英] Can't connect to local monogoDB from java

查看:155
本文介绍了无法从java连接到本地monogoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 环境:mac os x 10.10

  2. MongoDB版本:3.0.5

  3. JDK版本:1.8

  4. MongoDB驱动程序:mongo-java-driver-3.0.2.jar和
    mongodb-driver-async-3.0.2.jar

  1. Environment: mac os x 10.10
  2. MongoDB version: 3.0.5
  3. JDK version: 1.8
  4. MongoDB driver: "mongo-java-driver-3.0.2.jar" and "mongodb-driver-async-3.0.2.jar"

问题:

我想连接 mongoDB 并插入一些简单的数据异步,所以我用 mongodb-driver-async-3.0.2.jar 。但我发现我没有连接数据库。代码如下:

I want to connect mongoDB and insert some simple data by asynchronously,so I used "mongodb-driver-async-3.0.2.jar". But I found that I did not connect the database.Code is as follows:

public static void main(String[] args) {
        // connect to the local database server,default:127.0.0.1:27017
        MongoClient mongoClient = MongoClients.create();
        // get handle to "testDB" database
        MongoDatabase database = (MongoDatabase) mongoClient.getDatabase("testDB");
        SingleResultCallback<Void> callbackWhenFinished = new SingleResultCallback<Void>() {
            @Override
            public void onResult(final Void result, final Throwable t) {
                System.out.println("Operation Finished!");
            }
        };
        // get a handle to the "test" collection
        MongoCollection<Document> collection = database.getCollection("test");
        collection.insertOne(new Document("lala","hehe"),callbackWhenFinished);
    }

我确定我已经在127.0.0.1:27017启动了数据库服务,并且可以连接shell和非异步方法。
错误:

I'm sure I have started the database service at 127.0.0.1:27017, and with shell and non-asynchronous method can be connected. Error:


PrimaryServerSelector从群集描述中选择的服务器没有
ClusterDescription {type = UNKNOWN,connectionMode = SINGLE,
all = [ServerDescription {address = localhost:27017,type = UNKNOWN,
state = CONNECTING}]}。在超时之前等待30000毫秒

No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out


推荐答案

我针对自己的(运行)运行了你的代码MongoDB服务器,我可以看到同样的错误。令我震惊的是,错误显示在超时之前等待30000ms,但代码在不到30秒的时间内完成。这提供了一个问题的提示。

I ran your code against my own (running) MongoDB server, and I can see the same error. What struck me though was that the error says "Waiting 30000ms before timing out", but the code completes in much less than 30 seconds. This gives a hint as to what the issue is.

请记住这是异步的 - 因此您不能指望所有操作在同一个线程上顺序运行。实际发生的是 main 方法在您调用数据库完成之前完成。

Remember this is async - therefore you can't expect all the operations to run sequentially on the same thread. What's actually happening is the main method is finishing before your call to the database finishes.

如果您更改代码等待结果在结束前回来,你会得到更合理的结果。

If you alter your code to wait for the results to come back before terminating, you get a much more reasonable result.

代码:

public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    // connect to the local database server,default:127.0.0.1:27017
    MongoClient mongoClient = MongoClients.create();
    // get handle to "testDB" database
    MongoDatabase database = (MongoDatabase) mongoClient.getDatabase("testDB");
    SingleResultCallback<Void> callbackWhenFinished = new SingleResultCallback<Void>() {
        @Override
        public void onResult(final Void result, final Throwable t) {
            System.out.println("Operation Finished!");
            latch.countDown();
        }
    };
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    collection.insertOne(new Document("lala", "hehe"), callbackWhenFinished);

    latch.await();
}

结果:

Aug 11, 2015 9:31:34 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:4}] to localhost:27017
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 2]}, minWireVersion=0, maxWireVersion=3, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=1281647}
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:5}] to localhost:27017
Operation Finished!

顺便说一句,代码可以进一步简化,特别是因为你说你正在使用Java 8:

By the way, the code can be simplified even further, especially since you say you're using Java 8:

public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    // connect to the local database server,default:127.0.0.1:27017
    MongoClient mongoClient = MongoClients.create();
    // get handle to "testDB" database
    MongoDatabase database = mongoClient.getDatabase("testDB");
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    collection.insertOne(new Document("lala", "hehe"),
                         (result, t) -> {
                             System.out.println("Operation Finished!");
                             latch.countDown();
                         });

    latch.await();
}

这篇关于无法从java连接到本地monogoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆