无法从java连接到本地monogoDB

时间:2015-08-11 05:26:18

标签: java mongodb

  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的驱动器 - 异步-3.0.2.jar”
  5. 问题:

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

    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和非异步方法。 错误:

      

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

2 个答案:

答案 0 :(得分:11)

我在我自己的(正在运行的)MongoDB服务器上运行你的代码,我可以看到同样的错误。令我印象深刻的是,错误表示&#34;在超时之前等待30000ms&#34;但是代码在不到30秒的时间内完成。这提供了一个关于问题的提示。

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

如果您更改代码以等待结果在终止之前返回,则会得到更合理的结果。

代码:

main

结果:

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();
}

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

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!

答案 1 :(得分:0)

检查Mongo-java-driver和Mongodb-Driver-Async

的版本兼容性

就我而言,我使用的是Mongo-java-driver-3.4.0 和mongodb-driver-async-3.0.4

它解决了这个问题。

相关问题