I have the following log in my mongo console:
Tue Jul 23 17:20:01.301 [initandlisten] waiting for connections on port 27017
Tue Jul 23 17:20:01.401 [websvr]
MongoClient has internal connection pool. Maximum number of connections can be configured (default is 100). You can set it by using MongoClientOptions
like this:
MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(100)
.autoConnectRetry(true)
.build();
And then give these options to MongoClient (checked it in Mongo Java API v2.11.1). Connections in pool are maintained open (opening and closing connection is usually an expensive operation) so that they can be later reused.
I would also refactor your MongoDB client singleton using enum
for example to avoid putting synchronized
on this method.
Here is a sketch of what I mean:
public enum MongoDB {
INSTANCE;
private static final String MONGO_DB_HOST = "some.mongohost.com";
private Mongo mongo;
private DB someDB;
MongoDB() {
MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(100)
.autoConnectRetry(true)
.readPreference(ReadPreference.secondaryPreferred())
.build();
try {
mongo = new MongoClient(MONGO_DB_HOST, options);
} catch (UnknownHostException e) {
e.printStackTrace();
}
someDB = mongo.getDB("someDB");
//authenticate if needed
//boolean auth = someDB.authenticate("username", "password".toCharArray());
//if(!auth){
// System.out.println("Error Connecting To DB");
//}
}
public DB getSomeDB() {
return someDB;
}
//call it on your shutdown hook for example
public void close(){
mongo.close();
}
}
Then, you can access your database via
MongoDB.INSTANCE.getSomeDB().getCollection("someCollection").count();