什么是确保我编写的方案能够最大限度地减少与 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/