測試環境:PHP5.3 + mongo-1.1.4-php5.3vc6ts的php_mongo.dll
使用mongostat觀察發現:
1.mongostat本身也佔用一個資料庫連接
2.PHP的mongo擴充默使用短串連,類似如此代碼:new Mongo("mongodb://192.168.1.108/test"),這種短串連一般在超出變數範圍後會自己關閉
3.PHP也可以使用長串連:
for($i=0;$i<100;$i++)
{
//mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
//建立一個標識符為x的長串連
$conn=new Mongo("mongodb://192.168.1.108/test",array("persist" => "x"));
$arr=$conn->test->post->find();
foreach ( $arr as $key => $val ) {
echo "$key => ";
var_dum($val);
echo "<br/>";
}
}
使用這種長串連,執行整個迴圈,從始至終都只有一個串連,切頁面執行完畢以後,串連也不會被關閉。(這種長串連效能明顯比短串連要好得多)
3.長串連的使用必須要主機名稱,連接埠,標識符,使用者名稱以及密碼一樣才行,否則會重新建立一個長串連,英文原文如下:
For a persistent connection to be used, the hostname, port, persist string, and username and password (if given) must match an existing persistent connection. Otherwise, a new connection will be created with this identifying information
例如如下代碼就會建立100個長串連:<?php
require "index.php";
for($i=0;$i<100;$i++)
{
//mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
//每次建立長串連的標識符都不一樣
$conn=new Mongo("mongodb://192.168.1.108/test",array("persist" => strval ($i)));
$arr=$conn->test->post->find();
foreach ( $arr as $key => $val ) {
echo "$key => ";
//EchoArray ( $val );
var_dump($val);
echo "<br/>";
}
}
?>
4.主機名稱,連接埠,標識符,使用者名稱以及密碼一樣一樣的長串連也可能會建立多個,但是這需要大並發量才會出現,假設http://localhost/index.php的代碼如下:
for($i=0;$i<100;$i++)
{
//mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
//建立一個標識符為x的長串連
$conn=new Mongo("mongodb://192.168.1.108/test",array("persist" => "x"));
$arr=$conn->test->post->find();
foreach ( $arr as $key => $val ) {
echo "$key => ";
var_dum($val);
echo "<br/>";
}
}
如上代碼,假如我們寫一個程式使用非同步同時發送幾十乃至幾百個串連去請求http://localhost/index.php,使用mongostat觀察會發現建立了多個長串連。