为什么在一个请求中创建多个数据库连接是不好的做法? [英] Why is it bad practice to make multiple database connections in one request?

查看:434
本文介绍了为什么在一个请求中创建多个数据库连接是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关 PHP 中的单身人士的讨论让我越来越多地考虑这个问题。大多数人指示你不应该在一个请求中做一堆DB连接,我只是好奇你的推理是什么。我的第一个想法是你的脚本向DB提出这么多请求的费用,但后来我反驳自己的问题:不是多个连接使并发查询更有效率?


解决方案

数据库连接是有限的资源。一些DB具有非常低的连接限制,并且浪费连接是一个主要问题。通过消耗很多连接,您可能会阻止其他人使用数据库。



此外,在数据库中引入大量额外的连接不会有任何帮助,除非有资源在DB服务器上空闲。如果你有8个核心,只有一个被用来满足一个查询,那么肯定,使另一个连接可能有帮助。更有可能的是,您已经使用所有可用的内核。



如果您的数据库具有类似高利用率的任何内容,则添加额外的连接将不会帮帮我。这就像在一个应用程序中产生额外的线程,盲目地希望额外的并发将使处理更快。在某些情况下,它可能会 ,但在其他情况下,它只会减慢你,因为你thrash硬盘驱动器,浪费时间任务切换,并引入同步开销。


A discussion about Singletons in PHP has me thinking about this issue more and more. Most people instruct that you shouldn't make a bunch of DB connections in one request, and I'm just curious as to what your reasoning is. My first thought is the expense to your script of making that many requests to the DB, but then I counter myself with the question: wouldn't multiple connections make concurrent querying more efficient?

How about some answers (with evidence, folks) from some people in the know?

解决方案

Database connections are a limited resource. Some DBs have a very low connection limit, and wasting connections is a major problem. By consuming many connections, you may be blocking others for using the database.

Additionally, throwing a ton of extra connections at the DB doesn't help anything unless there are resources on the DB server sitting idle. If you've got 8 cores and only one is being used to satisfy a query, then sure, making another connection might help. More likely, though, you are already using all the available cores. You're also likely hitting the same harddrive for every DB request, and adding additional lock contention.

If your DB has anything resembling high utilization, adding extra connections won't help. That'd be like spawning extra threads in an application with the blind hope that the extra concurrency will make processing faster. It might in some certain circumstances, but in other cases it'll just slow you down as you thrash the hard drive, waste time task-switching, and introduce synchronization overhead.

这篇关于为什么在一个请求中创建多个数据库连接是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆