首页 文章资讯内容详情

[ mongoDB ] - MongoDB 连接池

2026-05-31 4 花语

本文内容纲要:

一.mongoDB中的连接池

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

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

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

Mongom=newMongo("localhost",27017); DBdb=m.getDB("mydb"); //getcollection DBCollectioncoll=db.getCollection("testCollection") //insert BasicDBObjectdoc=newBasicDBObject(); ... coll.insert(doc); [伪代码]

如果套用以前的经验,可能会想偏,引用官方文档的一句话可能会豁然开朗。

Note:TheMongoobjectinstanceactuallyrepresentsapoolofconnectionstothedatabase;youwillonlyneedoneobjectofclassMongoevenwithmultiplethreads.Seetheconcurrencydocpageformoreinformation.

TheMongoclassisdesignedtobethreadsafeandsharedamongthreads.Typicallyyoucreateonly1instanceforagivenDBclusteranduseitacrossyourapp.Ifforsomereasonyoudecidetocreatemanymongointances,notethat:

allresourceusagelimits(maxconnections,etc)applypermongoinstance todisposeofaninstance,makesureyoucallmongo.close()tocleanupresources

mongo实例其实已经是一个现成的连接池了,而且线程安全。这个内置的连接池默认初始了10个连接,每一个操作(增删改查等)都会获取一个连接,执行操作后释放连接。

二.连接池的重要参数

内置连接池有多个重要参数,分别是:

connectionsPerHost:每个主机的连接数 threadsAllowedToBlockForConnectionMultiplier:线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Outofsemaphorestogetdb”错误。 maxWaitTime:最大等待连接的线程阻塞时间 connectTimeout:连接超时的毫秒。0是默认和无限 socketTimeout:socket超时。0是默认和无限 autoConnectRetry:这个控制是否在一个连接时,系统会自动重试

其设置方式如下:

MongoOptionsopt=mongo.getMongoOptions(); opt.connectionsPerHost=10;//poolsize opt.threadsAllowedToBlockForConnectionMultiplier=10; //其他参数类似

详情参考mongoDBAPI:

FieldSummary boolean autoConnectRetry Iftrue,thedriverwillkeeptryingtoconnecttothesameserverincasethatthesocketcannotbeestablished. int connectionsPerHost ThemaximumnumberofconnectionsallowedperhostforthisMongoinstance. int connectTimeout Theconnectiontimeoutinmilliseconds. DBDecoderFactory dbDecoderFactory OverridetheDBCallbackfactory. DBEncoderFactory dbEncoderFactory Overridetheencodingfactory. String description Thedescriptionfor Mongo instancescreatedwiththeseoptions. boolean fsync The"fsync"valueoftheglobalWriteConcern. boolean j The"j"valueoftheglobalWriteConcern. long maxAutoConnectRetryTime ThemaximumamountoftimeinMStospendretryingtoopenconnectiontothesameserver. int maxWaitTime Themaximumwaittimeinmsthatathreadmaywaitforaconnectiontobecomeavailable. boolean safe If true thedriverwilluseaWriteConcernofWriteConcern.SAFEforalloperations. boolean slaveOk Deprecated. ReplacedinMongoDB2.0/JavaDriver2.7withReadPreference.SECONDARY SocketFactory socketFactory setsthesocketfactoryforcreatingsocketstomongodDefaultisSocketFactory.getDefault() boolean socketKeepAlive Thisflagcontrolsthesocketkeepalivefeaturethatkeepsaconnectionalivethroughfirewalls Socket.setKeepAlive(boolean) Defaultisfalse. int socketTimeout ThesockettimeoutinmillisecondsItisusedforI/Osocketreadandwriteoperations Socket.setSoTimeout(int) Defaultis0andmeansnotimeout. int threadsAllowedToBlockForConnectionMultiplier thismultiplier,multipliedwiththeconnectionsPerHostsetting,givesthemaximumnumberofthreadsthatmaybewaitingforaconnectiontobecomeavailablefromthepool. int w The"w"valueoftheglobalWriteConcern. int wtimeout The"wtimeout"valueoftheglobalWriteConcern.

三.连接池实践

packagecom.bts.dao.mongodb; importjava.net.UnknownHostException; importcom.bts.util.ConfTool; importcom.mongodb.DB; importcom.mongodb.Mongo; importcom.mongodb.MongoException; importcom.mongodb.MongoOptions; /** *@authorhuangfox *@data2012-4-1 *@emailhuangfox009@126.com *@desc */ publicclassMongoManager{ privatestaticMongomongo=null; privateMongoManager(){ } /** *根据名称获取DB,相当于是连接 * *@paramdbName *@return */ publicstaticDBgetDB(StringdbName){ if(mongo==null){ //初始化 init(); } returnmongo.getDB(dbName); } /** *初始化连接池,设置参数。 */ privatestaticvoidinit(){ StringconfFilePath=""; ConfToolconf=newConfTool(confFilePath); Stringhost=conf.getValue("host");//主机名 intport=newInteger(conf.getValue("port"));//端口 intpoolSize=newInteger(conf.getValue("poolSize"));//连接数量 intblockSize=newInteger(conf.getValue("blockSize"));//等待队列长度 //其他参数根据实际情况进行添加 try{ mongo=newMongo(host,port); MongoOptionsopt=mongo.getMongoOptions(); opt.connectionsPerHost=poolSize; opt.threadsAllowedToBlockForConnectionMultiplier=blockSize; }catch(UnknownHostExceptione){ //logerror }catch(MongoExceptione){ //logerror } } }

本文内容总结:

原文链接:https://www.cnblogs.com/huangfox/archive/2012/04/01/2428947.html