Prashant Biradar
Prashant Biradar

Reputation: 323

com.allanbank.mongodb Java Mongodb Async driver error - Could not bootstrap a connection to the MongoDB servers

I'm implementing web services using google guice framework, here I injected mongodb module with constructor initializes mongodb connection. Here for every method I am using MongoClient and do stuff then I close connection after getting results. The problem is that if there is extensive heavy computations connection get closed and give error could not bootstrap connection error. please find the way to implement mongodb connection that will keep alive or restart communicating...

   try{
        MongoDBModule module = new MongoDBModule();
        MongoClient mongoClient =  module.getMongoDBClient();
        MongoDatabase database  = mongoClient.getDatabase(m_client.getDatabaseName());
        MongoCollection collection = database.getCollection("CAMPUS_PROD");

        //do stuff with mongoclient

        mongoClient.close();

       return document.resuls
    }catch(IOException ie){
           // print exception
     }

Upvotes: 0

Views: 408

Answers (1)

Rob Moore
Rob Moore

Reputation: 3383

Like all MongoDB drivers you should not create and close the MongoClient per-request. Instead you want to find a way to create a MongoClient when the application starts and then close it when the application exits.

In your case I would have your Guice Binder create the MongoClient and then do a bind(...).toInstance(...). e.g.,

bind(MongoClient.class).toInstance(mongoClient);

In the classes that use the MongoClient you should not call close().

The "cannot bootstrap" error is caused when the first request triggers the MongoClient to discover the MongoDB cluster and we could not create a connection to any of the servers. This could easily be caused by the connection thrashing causing by opening and closing the MongoClient.

Upvotes: 1

Related Questions