A connection pool is implemented internally. Mongo objects are thread-safe, so you can create just one and use it safely in a multi-threaded environment. Therefore, we can use Mongo variables as
1. The Mongo object
implements a connection pool internally. Mongo objects are thread-safe, so you can create just one and use it safely in a multi-threaded environment. Therefore, we can use Mongo variables as member variables of a Singleton class to ensure that only one connection pool is created. The Mongo.close method will close all currently active connections. So make sure to call the close method when the web project is logged out from the Tomcat or GlassFish container.
2.DB object
The DB object can be obtained through the Mongo.get method and represents a connection to the database. By default, when a database query or update operation is completed, the connection will automatically return to the connection pool. We don't need to manually call the code back to the pool. As for how to implement it, my guess is that there are finally blocks inside the update, query, and save methods, and there is code in there that is also connected to the pool.
3. Manually return the connection to the pool
DB objects also allow multiple operations to be performed on one connection
requestStart will automatically return the connection to the pool The pool is invalid, so you must ensure that requestDone can be called. The finally block should be used here to be more strict.
Implements the Singleton mode of Lazy loading, and the member variable Mongo mongo will only be instantiated once. Pay attention to the connection pool size and reconnect settings.
【Related Recommendations】
2. MongoDB (6) Java operation mongodb addition, deletion, modification and query
3. Sharing an example tutorial of using Spring Boot to develop Restful programs
4. Detailed explanation of using Elasticsearch in spring Example tutorial
The above is the detailed content of Detailed explanation of issues that should be paid attention to when connecting to MongoDB Java. For more information, please follow other related articles on the PHP Chinese website!