一.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