无法从java连接到本地monogoDB

赵学智*_*赵学智 5 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-driver-async-3.0.2.jar"

问题:

我想连接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);
    }
Run Code Online (Sandbox Code Playgroud)

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

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

Tri*_*sha 11

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

请记住,这是异步的 - 因此您不能指望所有操作在同一个线程上顺序运行.实际发生的是该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();
}
Run Code Online (Sandbox Code Playgroud)

结果:

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!
Run Code Online (Sandbox Code Playgroud)

顺便说一句,代码可以进一步简化,特别是因为你说你正在使用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();
}
Run Code Online (Sandbox Code Playgroud)