略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Persistent Connections (version up to 1.1.4 *only*)

2024-11-14

Persistent Connections (version up to 1.1.4 *only*)

Note:

This section is not relevant for 1.2.0+. In 1.2.0+, connections are always persistent and managed automatically by the driver. If you are using a 1.2.x release (but not 1.3.x or later), see MongoPool for more information on pooling.

Creating new connection to the database is very slow. To minimize the number of connections that you need to make, you can use persistent connections. A persistent connection is saved by PHP, so you can use the same connection for multiple requests.

For example, this simple program connects to the database 1000 times:

<?php

for ($i=0$i<1000$i++) {
  
$m = new MongoClient();
}

?>

It takes approximately 18 seconds to execute. If we change it to use a persistent connection:

<?php

for ($i=0$i<1000$i++) {
  
$m = new MongoClient("localhost:27017", array("persist" => "x"));
}

?>

...it takes less than .02 seconds to execute, as it only makes one database connection.

Persistent connections need an identifier string (which is "x" in the above example) to uniquely identify them. For a persistent connection to be used, the hostname, port, persist string, and authentication credentials (username, password and database, if given) must match an existing persistent connection. Otherwise, a new connection will be created with this identifying information.

Persistent connections are highly recommended and should always be used in production unless there is a compelling reason not to. Most of the reasons that they are not recommended for relational databases are irrelevant to MongoDB.

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.

官方地址:https://www.php.net/manual/en/mongo.connecting.persistent.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3