Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Java Driver database connection pooling with Tomcat

According to the MongoDB Java driver documentation, database connection pooling is magically handled by the Mongo object.

Does this mean it is safe to create an instance of a singleton object which connects to the MongoDB database in a servlet that will run when Tomcat starts and not worry about configuring database connection pooling in Tomcat via the context.xml?

Is this the right way to think about it? Am I misunderstanding some basic concept of Tomcat / database connection pooling in general?

like image 813
anon Avatar asked Jan 10 '11 14:01

anon


People also ask

Does MongoDB support connection pooling?

Create and Use a Connection PoolEach MongoClient instance manages its own connection pool to the MongoDB cluster or node specified when the MongoClient is created. MongoClient objects are thread-safe in most drivers.

Can JDBC connect to MongoDB?

MongoDB works on concept of collection and document. Before you start connecting MongoDB in you need to make sure that you have MongoDB JDBC driver. If not, download the jar from the path Download mongo. jar and, add it to your classpath.

What is the default connection pool size in MongoDB?

100 ( maxPoolSize default 100 ) x 4 (application servers) = 400 (incoming connections to each mongod).

How does MongoDB connect to MongoClient in Java?

To connect: MongoClient client = MongoClients. create("<<MongoDB URI>>"); To connect to MongoDB on your local instance and default port, you can just omit the URI part of the above, or use a URI like 'mongodb://localhost:27017'.


1 Answers

We've been using the Java drivers via the CFMongoDB project and we use it as you describe, but in a ColdFusion application rather then in Java. Same idea though: one object is created and we reuse it and that object maintains the one connection to the Mongo server.

You can create one Mongo Java instance and it will maintain an internal pool of connections (default size of 10) - to you it's hidden and you don't need to worry about it. The Mongo Java docs recommend this:

http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency

We have it running in production now and there have been no issues. Multiple web request threads use the same Mongo instance and Mongo is quick enough to deal with this using it's internal pool (we're doing logging so it can write very fast!).

It is worth remembering to call close() on any instances that you are finished with - this will stop connections getting used up on the Mongo server over time:

http://api.mongodb.org/java/2.5-pre-/com/mongodb/Mongo.html#close()

So in summary, don't worry about configuring Tomcat.

Hope that helps!

like image 57
Ciaran Archer Avatar answered Sep 25 '22 03:09

Ciaran Archer