Problem:
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);
}
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:
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
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.
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.
Code:
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();
}
Result:
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!
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With