sql >> Database teknologi >  >> NoSQL >> MongoDB

Kan ikke oprette forbindelse til lokal mongoDB fra java

Jeg kørte din kode mod min egen (kørende) MongoDB-server, og jeg kan se den samme fejl. Det, der dog slog mig, var, at fejlen siger "Waiting 30000ms before timeout", men koden er færdig på meget mindre end 30 sekunder. Dette giver et hint om, hvad problemet er.

Husk at dette er asynkront - derfor kan du ikke forvente, at alle operationerne kører sekventielt på den samme tråd. Det, der faktisk sker, er main metoden afsluttes, før dit opkald til databasen afsluttes.

Hvis du ændrer din kode for at vente på, at resultaterne kommer tilbage, før du afslutter, får du et meget mere fornuftigt resultat.

Kode:

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

Resultat:

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!

Forresten kan koden forenkles endnu mere, især da du siger, du bruger 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();
}


  1. Hvad er forskellen på mongoose og mongoJS? Hvilken skal jeg bruge?

  2. MongoDB $uge

  3. MongoDB-forespørgsel:$nær med aggregering

  4. Test af REST-ruter med curl --data, returnerer 404