php - PDO 持久连接缓存要求

标签 php mysql caching pdo

什么是确保我编写的方案能够最大限度地减少与 MySQL 数据库的连接数的最佳方法?

目前,我的服务器上有一个 ubuntu/PHP/apache 设置,我将以下代码与 PDO 一起使用以确保持久连接:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

但是,我似乎一直有 10 个或更多连接。我不确定这是为什么。引自 php.net :

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

这是否意味着我必须编写 $dbh = null 来“关闭”并缓存连接?

最佳答案

根据定义,持久连接是一种未关闭的连接(即它持续存在);好处是 PHP 保持连接 到数据库以供其他脚本使用(即,无需在每次脚本运行时拆除和设置新的数据库连接)。

没有必要写$dbh = null,因为这实际上暗示了脚本执行的终止;但是,如果您想在脚本结束之前发出信号表明您已完成连接,则可以显式编写它(然后,PHP 的垃圾收集器将在某个时候释放资源并将其返回到连接池以供其他人使用)脚本的使用)。

如果您希望在每个脚本结束时关闭和销毁连接,请不要使用持久连接!

关于php - PDO 持久连接缓存要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19397274/

相关文章:

javascript - 许多 Canvas 对象导致 "InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable"

php - 克隆 Laravel 项目并安装 composer 和 npm 然后也给我错误 500 page not found

javascript - CodeIgniter 在菜单上添加一个子文件夹作为链接

修改cico dhcp池的php脚本

entity-framework - 在 Azure AppFabric 中缓存 Entity Framework 结果

java - 过期时间@cacheable spring boot

PHP:Stomp - 是否可以捕获 "send()"上的错误?

php - 如何使用 php if ($text like %admin%) 搜索文本

mysql - 如何在第一个查询中选择行但在第二个查询中不存在?

MySQL Inner Join - Unknown column on 子句