Test environment: php_cmd.dll of PHP5.3 + mongo-1.1.4-php5.3vc6ts
We can use stat to observe and find that:
1. mongostat also occupies a database connection.
2. PHP's mongo extension uses transient connections, similar to the Code: new Mongo ("mongodb: // 192.168.1.108/test"). These transient connections are usually closed when they are out of the variable scope.
3. PHP can also use persistent connections:
For ($ I = 0; I I <100; $ I ++)
{
// Mongodb: // [username: password @] host1 [: port1] [, host2 [: port2:],...]/db
// Create a persistent connection with the identifier 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/> ";
}
}
With this persistent connection, the entire loop is executed, and there is only one connection from the beginning. After the page is split, the connection will not be closed. (The performance of this persistent connection is much better than that of short connections)
3. For persistent connections, the host name, port, identifier, user name, and password must be the same. Otherwise, a persistent connection will be created again:
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
For example, the following code creates 100 persistent connections: <? Php
Require "index. php ";
For ($ I = 0; I I <100; $ I ++)
{
// Mongodb: // [username: password @] host1 [: port1] [, host2 [: port2:],...]/db
// Each time a persistent connection is created, the identifiers are different.
$ 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. long connections with the same host name, port, identifier, user name, and password may also be created, but this requires a large amount of concurrency. For example, http: // localhost/index. the php code is as follows:
For ($ I = 0; I I <100; $ I ++)
{
// Mongodb: // [username: password @] host1 [: port1] [, host2 [: port2:],...]/db
// Create a persistent connection with the identifier 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/> ";
}
}
The code above assumes that a program sends dozens or even hundreds of connections asynchronously to request http: // localhost/index. php. Use the persistent STAT command to check whether multiple persistent connections are created.