1. Mongo object
The Mongo object implements a connection pool. 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 callCodeReturn 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:
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 is instantiated only once. Pay attention to the connection pool size and reconnection settings.
Package COM. freebird. helper; import COM. mongoDB. mongo; import COM. mongoDB. using options; import COM. mongoDB. DB;/*** describe class dbmanager here. * example: * initialization: dbmanager. getinstance (). init ("74.208.78.5", 27017,200); * then, each time you get the database object * dbmanager through the following code. getinstance (). getdb (); * created: Sat Dec 17 10:45:24 2011 ** @ author <a href = "mailto: chenshu @ chunshu "> chenshu </a> * @ version 1.0 */public class dbmanager {public static final string db_name =" kaimei "; public static final string message_collection =" email "; public static dbmanager getinstance () {return innerholder. instance;}/*** creates a new <code> dbmanager </code> instance. **/private dbmanager () {} Private Static class innerholder {static final dbmanager instance = new dbmanager ();} public dB getdb () {return Mongo. getdb (db_name);} private Mongo; Public void Init (final string IP, int port, int poolsize) throws java.net. unknownhostexception {system. setproperty ("Mongo. poolsize ", String. valueof (poolsize); If (Mongo = NULL) {Mongo = new Mongo (IP, Port); then options Options = Mongo. getaskoptions (); options. autoconnectretry = true; options. connectionsperhost = poolsize ;}}}