Original link:Java operation MongoDB (connection pool)
The MONGO instance is actually a database connection pool, which has 10 links in the default connection pool. There is no need to re-implement this link pool, but we can change the configuration of this connection pool. Because the MONGO instance is a connection pool, it is best to have only one instance of MONGO in the project.
Common Configuration parameters:
connectionsperhost: Number of connections per host
threadsallowedtoblockforconnectionmultiplier: The number of thread queues, the result of which is multiplied by the above Connectionsperhost value is the maximum thread queue value. The "out of semaphores to get DB" error is thrown if the connection thread is fully queued.
maxwaittime: The maximum waiting time for a connected thread to block
connecttimeout: The milliseconds that the connection timed out. 0 is the default and unlimited
sockettimeout: The socket timed out. 0 is the default and unlimited
autoconnectretry: If this control is in a connection, the system will automatically retry
There are also many configurations that can be found in the MongoDB API.
Here's a look at the code:
[Java]View PlainCopyprint?
- Package Com.mongo.common;
- Import java.net.UnknownHostException;
- Import Com.mongodb.DB;
- Import Com.mongodb.Mongo;
- Import com.mongodb.MongoException;
- Import com.mongodb.MongoOptions;
- Public class Mongomanager {
- Private final static String HOST = "localhost"; Port
- Private final static int PORT = 27017; Port
- Private final static int poolsize = + ; Number of connections
- Private final static int BLOCKSIZE = 100; //wait Queue Length
- private static Mongo Mongo = null;
- Private Mongomanager () {}
- Static {
- Initdbprompties ();
- }
- public static DB Getdb (String dbName) {
- return Mongo.getdb (dbName);
- }
- /**
- * Initialize Connection Pool
- */
- private static void Initdbprompties () {
- //Other parameters to be added according to the actual situation
- try {
- MONGO = new Mongoclient (HOST, PORT);
- Mongooptions opt = mongo.getmongooptions ();
- Opt.connectionsperhost = poolsize;
- Opt.threadsallowedtoblockforconnectionmultiplier = BLOCKSIZE;
- } catch (Unknownhostexception e) {
- } catch (Mongoexception e) {
- }
- }
- }
When used, as follows:
[Java]View PlainCopyprint?
- /**
- * Save
- *
- * @param user
- * @throws unknownhostexception
- */
- public void Save (user user) throws unknownhostexception {
- DB Mymongo = Mongomanager.getdb ("Mymongo");
- Dbcollection usercollection = mymongo.getcollection ("user");
- DBObject dbo = (dbobject) json.parse (User.tojson ());
- Usercollection.insert (dbo);
- }
Java Operation MongoDB (Connection pool) (RPM)