[ mongoDB ] - MongoDB 连接池
来源:互联网 发布:海岛奇兵火炮升级数据 编辑:程序博客网 时间:2024/05/15 18:15
一.mongoDB中的连接池
刚上手MongoDB,在做应用时,受以前使用关系型数据库的影响,会考虑数据库连接池的问题!
关系型数据库中,我们做连接池无非就是事先建立好N个连接(connection),并构建成一个连接池(connection pool),提供去连接和归还连接等操作。
而在MongoDB中,我们先来看看怎么进行操作,以insert为例:
Mongo m = newMongo( "localhost", 27017 );DB db = m.getDB( "mydb" );//get collectionDBCollection coll = db.getCollection("testCollection")//insertBasicDBObject doc =new BasicDBObject();...coll.insert(doc);[伪代码]
如果套用以前的经验,可能会想偏,引用官方文档的一句话可能会豁然开朗。
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.
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 across your app. If for some reason you decide to create many mongo 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
mongo实例其实已经是一个现成的连接池了,而且线程安全。这个内置的连接池默认初始了10个连接,每一个操作(增删改查等)都会获取一个连接,执行操作后释放连接。
二.连接池的重要参数
内置连接池有多个重要参数,分别是:
- connectionsPerHost:每个主机的连接数
- threadsAllowedToBlockForConnectionMultiplier:线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
- maxWaitTime:最大等待连接的线程阻塞时间
- connectTimeout:连接超时的毫秒。0是默认和无限
- socketTimeout:socket超时。0是默认和无限
- autoConnectRetry:这个控制是否在一个连接时,系统会自动重试
其设置方式如下:
MongoOptions opt = mongo.getMongoOptions();opt.connectionsPerHost =10 ;//poolsizeopt.threadsAllowedToBlockForConnectionMultiplier =10;//其他参数类似
详情参考mongoDB API:
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
If true the 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 mongod Default is SocketFactory.getDefault()
boolean
socketKeepAlive
This flag controls the socket keep alive feature that keeps a connection alive through firewalls
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.
三.连接池实践
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.MongoException;import com.mongodb.MongoOptions; /** * @author huangfox * @data 2012-4-1 * @email huangfox009@126.com * @desc */public class MongoManager { privatestatic Mongo mongo = null; privateMongoManager() { } /** * 根据名称获取DB,相当于是连接 * * @param dbName * @return */ publicstatic DB getDB(String dbName) { if(mongo == null) { // 初始化 init(); } returnmongo.getDB(dbName); } /** * 初始化连接池,设置参数。 */ privatestatic void init() { String confFilePath =""; ConfTool conf =new ConfTool(confFilePath); String host = conf.getValue("host");// 主机名 intport = new Integer(conf.getValue("port"));// 端口 intpoolSize = new Integer(conf.getValue("poolSize"));// 连接数量 intblockSize = newInteger(conf.getValue("blockSize"));// 等待队列长度 // 其他参数根据实际情况进行添加 try{ mongo =new Mongo(host, port); MongoOptions opt = mongo.getMongoOptions(); opt.connectionsPerHost = poolSize; opt.threadsAllowedToBlockForConnectionMultiplier = blockSize; }catch (UnknownHostException e) { // log error }catch (MongoException e) { // log error } }}
- [ mongoDB ] - MongoDB 连接池
- [ mongoDB ] - MongoDB 连接池
- MongoDB连接池
- mongodb连接池管理机制
- MongoDB 连接池
- mongodb 连接池
- MongoDB 连接池
- mongoDB中的连接池
- mongoDB连接池
- mongoDB中的连接池
- mongodb连接池
- 自定义MongoDB连接池
- MongoDB 连接池
- mongodb连接
- MongoDB - 连接
- MongoDB - 连接
- MongoDB - 连接
- mongoDB的连接池问题
- Boost_1_55_0+StlPort5.2.1+VS2010在xp环境搭建
- eclipse ssh架构下 tomcat下 访问路
- 一些小小的编程技巧(慢慢添加)
- 交叉编译
- uvalive 6206 Reduce the Maintenance Cost
- [ mongoDB ] - MongoDB 连接池
- 【黑马程序员】 java笔记——异常
- 记录Scrollview里的setContentOffset的动画冲突问题
- 如何在web中打开数据库中的文件
- 财务数字大小写转换函数代码
- 向 ReportViewer 报表中添加自定义代码
- J2EE中使用Spring进行事务和异常设计
- 2.28 Displaying Progress with UIProgressView
- failed to load properties file for project "..."