每次都应该使用 PDO::ATTR_PERSISTENT 吗?
使用 PDO 建立与数据库的连接时,每次都应该使用 PDO 属性 PDO::ATTR_PERSISTENT 吗?它表示这会为该用户创建一个持久连接,并且每次请求数据库连接时都会获取相同的连接,而不是重新建立一个新连接。为什么这不是默认值?有什么理由不使用它?
When establishing a connection to a database using PDO, should the PDO attribute PDO::ATTR_PERSISTENT be used every time? It says that this creates a persistant connection for that user, and will grab that same connection instead of re-establishing a new one each time you ask for a database connection. Why isn't this the default? Is there any reason not to use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果没有正确处理事务,可能会导致事务中已有“新”持久连接,这可能会导致混乱。
只是由以下代码引起的一个简单情况:
请求 1:
请求 2:
顺便说一句,示例的正确版本是:
If you don't handle transaction correctly, it can lead to a "new" persistent connection already in a transaction, which can cause chaos.
Just one simple case caused by the following code:
Request 1:
Request 2:
BTW the correct version of example is:
持久连接的问题是 MySQL 可用的连接数量是有限的。如果出现问题并且该连接没有关闭,服务器将使其长时间保持打开状态。如果服务器耗尽连接,则与其关联的每个应用程序都将不可用,直到有人干预为止。
您可能会不时地遇到一些问题,并且在错误的情况下,如果没有注意到,资源过度使用的问题可能会持续数月,从而导致性能非常逐渐下降,并且系统利用率随着时间的推移而增加(一切都没有好处)。
这是一篇可以帮助您的好文章。它重点关注 MySQL,但大多数相同的想法可以推广到 DBMS 的各个领域。
PHP 持久连接是邪恶的吗?
The issue with persistant connections is that the number of connections available to MySQL is limited. If something goes wrong and that connection isn't closed, the server is going to leave it open for a long time. If the server runs out of connections, then every single application tied to it is going to be unavailable until someone intervenes.
You can probably expect something to go wrong from time to time, and under the wrong circumstances the problem of resource over-usage can leak into months if not noticed, leaving you with a very gradual degrade in performance and increase in system utilization over time (all for no gain).
Here is one good article that can help you. It focuses on MySQL, but most of the same thoughts can be generalized across the spectrum of DBMS's.
Are PHP persistent connections evil ?