一.mongoDB中的连接池

刚上手MongoDB,在做应用时,受以前使用关系型数据库的影响,会考虑数据库连接池的问题!

关系型数据库中,我们做连接池无非就是事先建立好N个连接(connection),并构建成一个连接池(connection pool),提供去连接和归还连接等操作。

而在MongoDB中,我们先来看看怎么进行操作,以insert为例:

Mongo m = new Mongo( "localhost" , 27017 );
DB db = m.getDB( "mydb" );
//get collection
DBCollection coll = db.getCollection("testCollection")
//insert
BasicDBObject 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 ;//poolsize
opt.threadsAllowedToBlockForConnectionMultiplier = 10;
//其他参数类似

详情参考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 
          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
{
    private static Mongo
mongo =
null;
 
    private MongoManager()
{
 
    }
 
    /**
     *
根据名称获取DB,相当于是连接
     *
     *
@param dbName
     *
@return
     */
    public static DB
getDB(String dbName) {
        if (mongo
==
null)
{
            //
初始化
            init();
        }
        return mongo.getDB(dbName);
    }
 
    /**
     *
初始化连接池,设置参数。
     */
    private static void init()
{
        String
confFilePath =
"";
        ConfTool
conf =
new ConfTool(confFilePath);
        String
host = conf.getValue(
"host");//
主机名
        int port
=
new Integer(conf.getValue("port"));//
端口
        int poolSize
=
new Integer(conf.getValue("poolSize"));//
连接数量
        int blockSize
=
new Integer(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中的连接池(转载)的更多相关文章

  1. MongoDB中的连接池

    参见 http://www.cnblogs.com/huangfox/archive/2012/04/01/2428947.html

  2. SpringBoot 整合mongoDB并自定义连接池

    SpringBoot 整合mongoDB并自定义连接池 得力于SpringBoot的特性,整合mongoDB是很容易的,我们整合mongoDB的目的就是想用它给我们提供的mongoTemplate,它 ...

  3. node-mysql中的连接池代码学习

    node-mysql是一个node.js下的mysql驱动,前段时间在处理连接池的问题上遇到了连接不释放的疑难杂症,虽已解决,但仍需总结经验避免下次重蹈覆辙.下面是node-mysql中的连接池的部分 ...

  4. Mybatis中的连接池

    Mybatis中DataSource的存取 MyBatis是通过工厂模式来创建数据源DataSource对象的,MyBatis定义了抽象的工厂接口:org.apache.ibatis.datasour ...

  5. WebSphere中数据源连接池太小导致的连接超时错误记录

    WebSphere中数据源连接池太小导致的连接超时错误记录. 应用连接超时错误信息: [// ::: CST] webapp E com.ibm.ws.webcontainer.webapp.WebA ...

  6. 使用MongoDB 2.6 C++驱动中的连接池

    .post p{text-indent: 2em;} MongoDB2.6的CXX驱动(mongo-cxx-driver-26compat),内置包含了数据库连接池,方便管理数据库连接,但是官方文档说 ...

  7. 在Tomcat中配置连接池和数据源

    1.DataSource接口介绍 (1)DataSource 概述 JDBC1.0原来是用DriverManager类来产生一个对数据源的连接.JDBC2.0用一种替代的方法,使用DataSource ...

  8. Spring框架中获取连接池的几种方式

    什么是数据库连接池? 数据库连接池是一种关键的有限的昂贵的资源,对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响到程序的性能指标.数据库连接池就是用来解决这些问题而提出的. 数据库连接 ...

  9. JSP(Servlet)中从连接池获取连接

    1) 建立连接. 2) 执行SQL. 3) 处理结果. 4) 释放资源. Connection pool:连接池 DataSource: LDAP ( Light directory access p ...

随机推荐

  1. CFNetwork学习总结

  2. Temporary Post Used For Theme Detection (da655c32-bc15-41ad-bf89-e76c1ec1bea7 - 3bfe001a-32de-4114-a6b4-4005b770f6d7)

    This is a temporary post that was not deleted. Please delete this manually. (997facfe-d420-4437-a222 ...

  3. python中的reduce

    python中的reduce内建函数是一个二元操作函数,他用来将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 func()(必须是一个二元操作函数)先对集合中的第1 ...

  4. BZOJ 4004 [JLOI 2015] 装备购买 解题报告

    哎这个题 WA 了无数遍...果然人太弱... 首先我们把这些装备按照花费从小到大排序,然后依次考虑是否能买这个装备. 至于这样为什么是对的,好像有一个叫拟阵的东西可以证明,然而我不会.TATQAQ ...

  5. Vases and Flowers

    hdu4614:http://acm.hdu.edu.cn/showproblem.php?pid=4614 题意:给你n个花瓶,然后有两种操作:1从a开始选择b个花瓶,放进花,输出左端点,右端点 2 ...

  6. 禁用nginx的access日志

    修改nginx.conf 找到access_log: access_log /dev/null; 或者access_log off

  7. eCos中断模型

    http://blog.csdn.net/chychc/article/details/8313458 http://www.cnblogs.com/RandyQ/archive/2013/04/14 ...

  8. solr的原子更新/局部更新

    solr支持三种类型的原子更新: set - to set a field. add - to add to a multi-valued field. inc - to increment a fi ...

  9. stream_iterator、ostream_iterator 使用初探

    STL定义了供输入及输出的iostream iterator类,称为 istream_iterator和ostream_iterator,分别支持单一型别的元素的读取和写入. 使用方法: 1.包含头文 ...

  10. 存储过程系列之存储过程sql数据库调用和程序代码调用

    1.存储过程,无参数的存储过程 创建无参数存储存储过程 Create Procedure DCEMREMR_TEMPLATEAs SELECT TOP 10 [FILENAME],[FILETITLE ...