[英]PHP - MongoClient connections stacking up, not closing
我有一個可以從Mongo數據庫中提取和匯總數據的類。 一切正常...我在同一個連接(在同一類中)下針對一個連接運行多個查詢。 但是,每次刷新頁面時,都會打開一個新連接...在mongod輸出中可以看到以下內容:
[initandlisten] connection accepted from 127.0.0.1:46770 #12 (6 connections now open)
我看到這一點隨着每次頁面刷新而增加。 我認為這應該很好。 但是,連接似乎從未關閉 。
一段時間后,連接/鎖在Mongo中占用了太多內存,並且我無法再運行查詢。
這個開發環境在Mongo的32位版本上,所以我不知道是否只是因為這個原因而發生。 (我們的產品環境是64位的,我現在不能更改開發環境。)
我的問題是: 對特定用戶進行所有查詢后,我應該關閉連接嗎? 我應該如何處理連接池?
服務類別:
class MongoService{
protected $mongoServer;
public function setSpokenlayerMongoServer($mongoServer)
{ $this->mongoServer = $mongoServer; }
protected $mongoUser;
public function setSpokenlayerMongoUser($mongoUser)
{ $this->mongoUser = $mongoUser; }
protected $mongoPassword;
public function setSpokenlayerMongoPassword($mongoPassword)
{ $this->mongoPassword = $mongoPassword; }
protected $conn;
public function setServiceConnection($conn)
{ $this->conn = $conn; }
public function connect(){
try {
$this->conn = $this->getMongoClient();
} catch(Exception $e) {
/* Can't connect to MongoDB! */
// logException($e);
die("Can't do anything :(");
}
}
public function getDatabase($name){
if(!isset($this->conn)){
$this->connect();
}
return $this->conn->$name;
}
protected function getMongoClient($retry = 3) {
$connectString= "mongodb://".$this->mongoUser.":".$this->mongoPassword."@". $this->mongoServer."";
try {
return new MongoClient($connectString);
} catch(Exception $e) {
/* Log the exception so we can look into why mongod failed later */
// logException($e);
}
if ($retry > 0) {
return $this->getMongoClient(--$retry);
}
throw new Exception("I've tried several times getting MongoClient.. Is mongod really running?");
}
}
在查詢所在的服務類中:
protected function collection(){
if(!isset($this->collection)){
$this->collection = $this->db()->selectCollection($this->collectionName);
}
return $this->collection;
}
然后執行查詢,如下所示:
$results = $this->collection()->aggregate($ops);
這是正確的行為嗎?
如果您使用的是Azure IaaS,則已知的問題,在其他平台上可能會出現問題。
一種選擇是更改Mongo配置:
MongoDefaults.MaxConnectionIdleTime = TimeSpan.FromMinutes(5);
5分鍾后,這將殺死所有空閑連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.