1. Mongo object
A connection pool is implemented internally. Mongo objects are thread-safe. Therefore, you can create only one Mongo object and use it safely in a multi-threaded environment. Therefore, we can use the Mongo variable as a member variable of the Singleton class to ensure that only one connection pool is created. The Mongo. close method will close all currently active connections. Make sure to call the close method when the web project is deregistered from the Tomcat or GlassFish container.
2. DB object
The DB object can be obtained through the Mongo. get method, representing a connection to the database. By default, after the database query or update operation is completed, the connection will automatically return to the connection pool. We do not need to manually call the code back to the pool. As for how to implement it, I guess there are finally blocks in the update, query, and save methods, and the code is also connected to the pool.
3. manually connect to the pool
The DB object can also perform multiple operations on a connection, such as the following code:
[Java]
- DB db ...;
- Db. requestStart ();
- Code ....
- Db. requestDone ();
RequestStart will invalidate the automatic connection to the pool. Therefore, ensure that requestDone can be called. The finally block should be more rigorous here.
4. Sample Code. The following class implements the Singleton mode of Lazy loading. The member variable Mongo mongo is instantiated only once. Pay attention to the connection pool size and reconnection settings.
[Java]
- PackageCom. freebird. helper;
- ImportCom. mongodb. Mongo;
- ImportCom. mongodb. MongoOptions;
- ImportCom. mongodb. DB;
- /**
- * Describe class DBManager here.
- * Example:
- * Initialization: DBManager. getInstance (). init ("74.208.78.5", 27017,200 );
- * Then, each time the following code is used to obtain the database object
- * DBManager. getInstance (). getDB ();
- * Created: Sat Dec 17 10:45:24 2011
- *
- * @ Author <a href = "mailto: chenshu @ chunshu"> chenshu </a>
- * @ Version 1.0
- */
- Public ClassDBManager {
- Public Static FinalString DB_NAME ="Kaimei";
- Public Static FinalString MESSAGE_COLLECTION ="Email";
- Public StaticDBManager getInstance (){
- ReturnInnerHolder. INSTANCE;
- }
- /**
- * Creates a new <code> DBManager </code> instance.
- *
- */
- PrivateDBManager (){
- }
- Private Static ClassInnerHolder {
- Static FinalDBManager INSTANCE =NewDBManager ();
- }
- PublicDB getDB (){
- ReturnMongo. getDB (DB_NAME );
- }
- PrivateMongo mongo;
- Public VoidInit (FinalString ip,IntPort,IntPoolSize)ThrowsJava.net. UnknownHostException {
- System. setProperty ("MONGO. POOLSIZE", String. valueOf (poolSize ));
- If(Mongo =Null){
- Mongo =NewMongo (ip, port );
- Optional options = mongo. getmediaoptions ();
- Options. autoConnectRetry =True;
- Options. connectionsPerHost = poolSize;
- }
- }
- }