在关系型数据库中,咱们老是须要关闭使用的数据库链接,否则大量的建立链接会致使资源的浪费甚至于数据库宕机。这篇文章主要想解释一下mongoDB的链接池以及链接管理机制,若是正对此有疑惑的朋友能够看一下。javascript
一般咱们习惯于new 一个connection而且一般在finally语句中调用connection的close()方法将其关闭。正巧,mongoDB中当咱们new一个Mongo的时候,会发现它也有一个close()方法。因此会出现这样的状况:咱们在须要DB操做的方法中new一个mongo实例,而后调用mongo.getDB()方法拿到对应的链接,操做完数据以后再调用mongo.close()方法来关闭链接。 看起来貌似是没有什么问题,可是若是你再研究一下mongo的API,你会发现这样耳朵操做就至关于园丁在浇花的时候去打了一桶水,而后舀了一勺水浇一朵花,而后他把一桶水全倒了回去,从新打一桶水,再舀了一勺水浇另一朵花。。。java
说到这里你们应该都已经明白了,其实当你new Mongo()的时候,就建立了一个链接池,getDB()只是从这个链接池中拿一个可用的链接。而链接池是不须要咱们及时关闭的,咱们能够在程序的生命周期中维护一个这样的单例,至于从链接池中拿出的链接,咱们须要关闭吗?答案是NO。你会发现DB根本没有close()之类的方法。在mongoDB中,一个链接池会维持必定数目的链接,当你须要的时候调用getDB()去链接池中拿到链接,而mongo会在这个DB执行完数据操做时候自动收回链接到链接池中待用。因此在mongoDB中你们没必要担忧链接没有关闭的问题,在你须要在全部操做结束或者整个程序shutdown的时候调用mongo的close()方法便可。数据库
如下的官网的一些解释:app
public Class Mongo:this
A database connection with internal connection pooling. For most applications, you should have one Mongo instance for the entire JVM.spa
public Class MongoClient:code
A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.server
Note: This class supersedes the Mongo
class. While it extends Mongo
, it differs from it in that the default write concern is to wait for acknowledgment from the server of all write operations. In addition, its constructors accept instances of MongoClientOptions
and MongoClientURI
, which both also set the same default write concern.blog
In general, users of this class will pick up all of the default options specified in MongoClientOptions
. In particular, note that the default value of the connectionsPerHost option has been increased to 100 from the old default value of 10 used by the superceded Mongo
class.生命周期
Mongo 是一个过时的类,取而代之的是MongoClient, 值得一提的是MongoClient把connection的默认值从之前的10个变成了如今的100个,省去了自定义配置的繁琐,很贴心。
下面是我写的一个MongoConnectionFactory:
Java代码
原创文章,转载请注明出处: