在關係型數據庫中,咱們老是須要關閉使用的數據庫鏈接,否則大量的建立鏈接會致使資源的浪費甚至於數據庫宕機。這篇文章主要想解釋一下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代碼
原創文章,轉載請註明出處: