Singleton MongoDBClient for Java Application
Reason to recommend not to close MongoDB driver connection:-
The MongoDB Java driver provides a MongoClient class for the connection of your Java application with the MongoDB database.
The mongodb java client maintains (example below) a connection pool, which is relatively expensive to set up [even in faster network it takes 100 of milliseconds, apart from that each driver connection would run in separate thread and it will consume memory], so one should reuse the MongoClient instance across the lifetime.
A Connection Pool is a cache of database connections maintained by the driver so that connections can be reused when new connections to the database are required. To reduce the number of connection pools created by your application, it is recommend to call MongoClient.connect once.
So it becomes obvious to create one instance of the MongoClient and to reuse it in every request of your application and not to close it.
MongoDBServices wrapper class:-
- I kept separate properties file which has parameters to connect with MongoDB server.
- Declaration and Initialization of MongoClient.
- Use method for database operation.
Singleton pattern in Java by using enum
Parameters to connect with MongoDB server
Properties file holding details for connection. |
Declaration and Initialization of MongoClient
| ||
Use method for database operation
| ||