mongodb connection pooling
Asked Answered
C

3

10

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?

Capitally answered 23/1, 2012 at 6:54 Comment(1)
possible duplicate of MongoDB Java Driver database connection pooling with TomcatMargarito
H
21

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

Haloid answered 23/1, 2012 at 7:10 Comment(1)
You should definitely avoid multiple clients for a single application. You want to minimize the total number of connections into a MongoDB deployment since each one requires almost 1MB of RAM in overhead meaning less available for cache.Westerly
H
5

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.

Haletky answered 15/2, 2019 at 17:3 Comment(1)
The link you provided does not discuss connection poolingHardspun
H
2

You can set max pool size mongodb://***/?maxPoolSize=5 for detail Review this documentation https://docs.mongodb.com/manual/reference/connection-string/

Hindi answered 14/9, 2016 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.