MongoDB connection pool introduction, important parameters of the connection pool and connection pool practices, mongodb Parameters

Source: Internet
Author: User
Tags time in milliseconds keep alive

MongoDB connection pool introduction, important parameters of the connection pool and connection pool practices, mongodb Parameters
I. mongoDB connection pool

When using MongoDB, the database connection pool will be considered due to the impact of the previous use of relational databases!

In relational databases, the connection pool is nothing more than establishing N connections in advance, and building a connection pool, which provides operations such as de-connection and return of connections.

In MongoDB, let's take a look at how to perform the operation. Take insert as an example:

Mongo m = new Mongo ("localhost", 27017); DB db = m. getDB ("mydb"); // get collectionDBCollection coll = db. getCollection ("testCollection") // insertBasicDBObject doc = new BasicDBObject ();... coll. insert (doc); [pseudo code]

If you use your previous experience, you may be confused.

Note: The Mongo object instance actually represents a pool of connections to the database; you will only need one object of class Mongo even with multiple threads. see the concurrency doc page for more information. if you use your previous experience, you may be confused.

The Mongo class is designed to be thread safe and shared among threads. typically you create only 1 instance for a given DB cluster and use it your SS your app. if for some reason you decide to create mongomongo intances, note that:

All resource usage limits (max connections, etc) apply per mongo instance

To dispose of an instance, make sure you call mongo. close () to clean up resources

The mongo instance is already a ready-made connection pool and thread security. This built-in connection pool has 10 initial connections by default. Each operation (such as adding, deleting, modifying, and querying) will obtain a connection, and the connection will be released after the operation is executed.

Ii. Important Parameters of the Connection Pool

The built-in connection pool has multiple important parameters:

ConnectionsPerHost: Number of connections per host

ThreadsAllowedToBlockForConnectionMultiplier: Number of thread queues. The result of multiplying the connectionsPerHost value above is the maximum value of the thread queue. If the connection thread is full, the error "Out of semaphores to get db" will be thrown.

MaxWaitTime: Maximum thread blocking time waiting for connection

ConnectTimeout: the connection timeout time in milliseconds. 0 is the default and unlimited

SocketTimeout: socket timeout. 0 is the default and unlimited

AutoConnectRetry

The configuration method is as follows:

Optional options opt = mongo. getaskoptions (); opt. connectionsPerHost = 10; // poolsizeopt. threadsAllowedToBlockForConnectionMultiplier = 10; // other parameters are similar

For more information, see mongoDB API:

Field Summary
Boolean

AutoConnectRetry

If true, the driver will keep trying to connect to the same server in case that the socket cannot be established.

Int

ConnectionsPerHost

The maximum number of connections allowed per host for this Mongo instance.

Int

ConnectTimeout

The connection timeout in milliseconds.

DBDecoderFactory

DbDecoderFactory

Override the DBCallback factory.

DBEncoderFactory

DbEncoderFactory

Override the encoding factory.

String

Description

The description for Mongo instances created with these options.

Boolean

Fsync

The "fsync" value of the global WriteConcern.

Boolean

J

The "j" value of the global WriteConcern.

Long

MaxAutoConnectRetryTime

The maximum amount of time in MS to spend retrying to open connection to the same server.

Int

MaxWaitTime

The maximum wait time in MS that a thread may wait for a connection to become available.

Boolean

Safe

IfTrueThe driver will use a WriteConcern of WriteConcern. SAFE for all operations.

Boolean

SlaveOk

Deprecated. Replaced in MongoDB 2.0/Java Driver 2.7 with ReadPreference. SECONDARY

SocketFactory

SocketFactory

Sets the socket factory for creating sockets to require D Default is SocketFactory. getDefault ()

Boolean

SocketKeepAlive

This flag controls the socket keep alive feature that keeps a connection alive through firewils Socket. setKeepAlive (boolean) Default is false.

Int

SocketTimeout

The socket timeout in milliseconds It is used for I/O socket read and write operations Socket. setSoTimeout (int) Default is 0 and means no timeout.

Int

ThreadsAllowedToBlockForConnectionMultiplier

This multiplier, multiplied with the connectionsPerHost setting, gives the maximum number of threads that may be waiting for a connection to become available from the pool.

Int

W

The "w" value of the global WriteConcern.

Int

Wtimeout

The "wtimeout" value of the global WriteConcern.

Iii. Connection Pool practices
Package com. bts. dao. mongodb; import java.net. unknownHostException; import com. bts. util. confTool; import com. mongodb. DB; import com. mongodb. mongo; import com. mongodb. except exception; import com. mongodb. using options;/*** @ author huangfox * @ data 2012-4-1 * @ email huangfox009@126.com * @ desc */public class merge manager {private static Mongo mongo = null; private merge Manager () {}/*** get the database by name, equivalent to the connection ** @ Param dbName * @ return */public static DB getDB (String dbName) {if (mongo = null) {// initialize init ();} return mongo. getDB (dbName);}/*** initialize the connection pool and set parameters. */Private static void init () {String confFilePath = ""; ConfTool conf = new ConfTool (confFilePath); String host = conf. getValue ("host"); // host name int port = new Integer (conf. getValue ("port"); // port int poolSize = new Integer (conf. getValue ("poolSize"); // Number of connections int blockSize = new Integer (conf. getValue ("blockSize"); // wait for the queue length // Add other parameters as needed try {mongo = new Mongo (host, port); Optional options opt = mongo. getaskoptions (); opt. connectionsPerHost = poolSize; opt. threadsAllowedToBlockForConnectionMultiplier = blockSize;} catch (UnknownHostException e) {// log error} catch (unknown exception e) {// log error }}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.