无法从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”

问题:

我想连接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 callbackWhenFinished = new SingleResultCallback() { @Override public void onResult(final Void result, final Throwable t) { System.out.println("Operation Finished!"); } }; // get a handle to the "test" collection MongoCollection 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,state = CONNECTING}]}。 超时前等待30000毫秒

我在我自己的(正在运行的)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 callbackWhenFinished = new SingleResultCallback() { @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 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:

 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 collection = database.getCollection("test"); collection.insertOne(new Document("lala", "hehe"), (result, t) -> { System.out.println("Operation Finished!"); latch.countDown(); }); latch.await(); } 

检查Mongo-java-driver和Mongodb-Driver-Async的版本兼容性

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

它解决了这个问题。