測試環境:PHP5.3+ mongo-1.1.4-php5.3vc6ts的php_mongo.dll
使用mongostat觀察發現:
1.mongostat本身也占用一個資料庫連接配接
2.PHP的mongo擴充默使用短連接配接,類似如此代碼:newMongo("mongodb://192.168.1.108/test"),這種短連接配接一般在超出變量作用域後會自己關閉
3.PHP也可以使用長連接配接:
for($i=0;$i<100;$i++)
{
//mongodb://[username:[email protected]]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 "
";
}
}
使用這種長連接配接,執行整個循環,從始至終都隻有一個連接配接,切頁面執行完畢以後,連接配接也不會被關閉。(這種長連接配接性能明顯比短連接配接要好得多)
3.長連接配接的使用必須要主機名,端口,辨別符,使用者名以及密碼一樣才行,否則會重新建立一個長連接配接,英文原文如下:
For a persistent connection to be used, the hostname, port,persist string, and username and password (if given) must match anexisting persistent connection. Otherwise, a new connection will becreated with this identifying information
例如如下代碼就會建立100個長連接配接:
require "index.php";
for($i=0;$i<100;$i++)
{
//mongodb://[username:[email protected]]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 "
";
}
}
?>
4.主機名,端口,辨別符,使用者名以及密碼一樣一樣的長連接配接也可能會建立多個,但是這需要大并發量才會出現,假設http://localhost/index.php的代碼如下:
for($i=0;$i<100;$i++)
{
//mongodb://[username:[email protected]]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 "
";
}
} 如上代碼,假如我們寫一個程式使用異步同時發送幾十乃至幾百個連接配接去請求http://localhost/index.php,使用mongostat觀察會發現建立了多個長連接配接。