剛上手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 |