zoukankan      html  css  js  c++  java
  • 关于PHP与MongoDB的一些杂记

    测试环境: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观察会发现创建了多个长连接。
  • 相关阅读:
    Azure 认知服务 (3) 计算机视觉API
    Azure 认知服务 (2) 计算机视觉API
    Azure 认知服务 (1) 概述
    Azure PowerShell (13) 批量设置Azure ARM Network Security Group (NSG)
    Azure SQL Database (22) Azure SQL Database支持中文值
    HighCharts设置图表背景透明
    跨域资源共享(CORS)--跨域ajax
    "Ext 4.1 Grid 'el.dom' 为空或不是对象"问题的解决
    Ant编译utf-8非法字符:/65279 解决方法
    lvs 隧道模式请求没有回应的解决
  • 原文地址:https://www.cnblogs.com/mxw09/p/2156306.html
Copyright © 2011-2022 走看看