mongoDB 长/短连接

http://hi.baidu.com/gujianghua5712/blog/item/8b58265068d5ee3943a75b33.html

测试环境: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: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 anexisting persistent connection. Otherwise, a new connection will becreated 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观察会发现创建了多个长连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值