Home > Java > javaTutorial > body text

Detailed explanation of issues that should be paid attention to when connecting to MongoDB Java

零下一度
Release: 2017-05-26 14:16:22
Original
1898 people have browsed it

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】

1. Share an example tutorial on connecting Java to MongoDB for addition, deletion, modification and query

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template