Mongodb open connection problem

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] admin web console waiting for connections on port 28017 Tue Jul 23 17:20:01.569 [initandlisten] connection accepted from 127.0.0.1:58090 #1 (1 connection now open) Tue Jul 23 17:20:01.570 [initandlisten] connection accepted from 127.0.0.1:58089 #2 (2 connections now open) Tue Jul 23 17:20:21.799 [initandlisten] connection accepted from 127.0.0.1:58113 #3 (3 connections now open) .... .... .... 

Similarly, the log continues, and now it is at 112. Each time I start the mongo server, this happens. I only have a single point connection in my code. What could be here:

 public static DB getConnection(String databaseName) throws AppConnectionException { if (null != db) { Logger.debug("Returning existing db connection...!"); return db; } Logger.debug("Creating new db connection...!"); final String connStr = PropertyRetreiver.getPropertyFromConfigurationFile("rawdata.url"); try { final MongoClientURI uri = new MongoClientURI(connStr); final MongoClient client = new MongoClient(uri); db = client.getDB(databaseName); } catch (UnknownHostException e) { throw new AppConnectionException( "Unable to connect to the given host / port."); } return db; } 
+6
source share
1 answer

MongoClient has an internal connection pool. You can configure the maximum number of connections (default is 100). You can install it using MongoClientOptions as follows:

 MongoClientOptions options = MongoClientOptions.builder() .connectionsPerHost(100) .autoConnectRetry(true) .build(); 

And then give these parameters to MongoClient (check it in Mongo Java API v2.11.1). Connections in the pool are kept open (opening and closing connections is usually an expensive operation) so that they can later be reused.

I would also reorganize your singleton MongoDB client using enum , for example, so as not to put synchronized in 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 through

 MongoDB.INSTANCE.getSomeDB().getCollection("someCollection").count(); 
+8
source

Source: https://habr.com/ru/post/950081/


All Articles