问题
I am using Java driver to access mongodb. I assume the db connection pooling is internally handled by the driver.But my connection count getting increased every time I access db.
This is my serverStatus log.
"connections" : {
"current" : 276,
"available" : 543
}
Do I need to explicitly close mongo connections? how should I manage connection pooling in java?
回答1:
You should use a single Mongo object, so it will do pooling for you. However, if you do use multiple objects, you do need to call .close()
explicitly.
From: http://www.mongodb.org/display/DOCS/Java+Tutorial
The Mongo class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given DB cluster and use it across your app. If for some reason you decide to create many mongo intances, note that:
all resource usage limits (max connections, etc) apply per mongo instance to dispose of an instance, make sure you call mongo.close() to clean up resources
回答2:
You can set max pool size mongodb://***/?maxPoolSize=5 for detail Review this documentation https://docs.mongodb.com/manual/reference/connection-string/
回答3:
MongoDB, MongoDB is act as connection pool for mongoDB and it is created per application and per DB basis.
Typically you only create one MongoClient instance for a given MongoDB deployment (e.g. standalone, replica set, or a sharded cluster) and use it across your application. However, if you do create multiple instances:
All resource usage limits (e.g. max connections, etc.) apply per MongoClient instance.
Ref: http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/connect-to-mongodb/
MongoClientOptions options =
MongoClientOptions.builder()
.threadsAllowedToBlockForConnectionMultiplier(prop.getThreadsAllowedToBlock())
.connectionsPerHost(pro.getConnectionsPerHost())
.connectTimeout(prop.getConnectionTimeout())
.maxWaitTime(prop.getConnectionTimeout())
.socketTimeout(1000)
.heartbeatConnectTimeout(prop.getHeartbeatConnectTimeout())
.writeConcern(WriteConcern.ACKNOWLEDGED).build();
MongoClient mongoclient = new MongoClient(seeds,credential, options); credential, options);
This is working as connection pool. We can instantiate MongoTemplate from MongoClient.
来源:https://stackoverflow.com/questions/8968125/mongodb-connection-pooling