關於PHP與MongoDB的一些雜記

來源:互聯網
上載者:User

測試環境: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觀察會發現建立了多個長串連。

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.