sql >> Base de Datos >  >> NoSQL >> MongoDB

No se puede conectar a mongoDB local desde Java

Ejecuté su código contra mi propio servidor MongoDB (en ejecución), y puedo ver el mismo error. Sin embargo, lo que me llamó la atención fue que el error dice "Esperando 30000 ms antes de que se agote el tiempo de espera", pero el código se completa en mucho menos de 30 segundos. Esto da una pista de cuál es el problema.

Recuerde que esto es asíncrono; por lo tanto, no puede esperar que todas las operaciones se ejecuten secuencialmente en el mismo subproceso. Lo que realmente está sucediendo es el main el método está finalizando antes de que finalice su llamada a la base de datos.

Si modifica su código para esperar a que regresen los resultados antes de terminar, obtendrá un resultado mucho más razonable.

Código:

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

Resultado:

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!

Por cierto, el código se puede simplificar aún más, especialmente porque dices que estás usando 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();
}