database - 为什么一个包含许多打开的连接的连接池对于系统来说比每次打开一个新连接的成本要低?

标签 database connection-pooling

来自here的回答

Typically, opening a database connection is an expensive operation, so pooling keeps the connections active so that, when a connection is later requested, one of the active ones is used in preference to opening another one.

我了解数据库管理中连接池的概念。这是“什么是 ~”问题的答案。所有开发人员的博客文章、答案、教程、数据库文档总是回答“什么是”这个问题。就像他们不断地相互复制/粘贴文本一样。没有人试图解释“为什么会这样”和“如何”。上面的答案就是一个例子。

我无法理解为什么如何在池中保持 30 个打开的连接对于系统来说比打开一个新的连接成本更低需要时连接。

假设,我有一个位于澳大利亚的网络服务器。 AWS 中的一个数据库位于美国俄勒冈州的某个地方。或者在 GB 中。或者离 AUS 很远的任何地方。所以他们都说,在这种情况下,保持一个 20-... 打开的连接池对于内存和系统性能的成本要比每次打开一个新连接的成本低?怎么可能?为什么?

最佳答案

在您的场景中,我认为最大的问题是网络延迟。您不能指望位于两个不同大陆的服务器之间的通信速度特别快。因此,如果您每次需要时都启动一个新连接,那么您每次都会遇到这种延迟。

来自 here :

Connecting to a database server typically consists of several time-consuming steps. A physical channel such as a socket or a named pipe must be established, the initial handshake with the server must occur, the connection string information must be parsed, the connection must be authenticated by the server, checks must be run for enlisting in the current transaction, and so on.

此外,如果网络服务器和数据库之间的连接使用 SSL/TLS,则必须在实际通信发生之前在每个新连接上执行一次握手(除了正常的握手之外在正常连接中发生)。这种握手在时间上是昂贵的。

来自 here :

Before the client and the server can begin exchanging application data over TLS, the encrypted tunnel must be negotiated: the client and the server must agree on the version of the TLS protocol, choose the ciphersuite, and verify certificates if necessary. Unfortunately, each of these steps requires new packet roundtrips between the client and the server, which adds startup latency to all TLS connections. (...) As the above exchange illustrates, new TLS connections require two roundtrips for a "full handshake"—that’s the bad news

当您使用连接池时,可以通过不时定期向 SQL Server 发送类似“ping”的消息来避免这种开销,以避免连接因不活动而超时。当然,这可能会消耗您服务器中的更多内存,但现在这是一种便宜得多的资源。网络延迟是不可避免的。

关于database - 为什么一个包含许多打开的连接的连接池对于系统来说比每次打开一个新连接的成本要低?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44081488/

相关文章:

database - DBInputFormat多记录处理

sql-server - Ado.net (2.0+) 连接池是在应用程序域之前还是每个进程

node.js - 如何在 Node.js Web 应用程序中管理 MongoDB 连接?

tomcat - 在java中创建连接池

oracle - WSO2 Identity Server - 自定义 JDBC 用户存储管理器 - JDBC 池

mysql - 如何创建按标签组织的数据库

sql - 使外键也成为 Rails 迁移中的主键

mysql - 如何选择中值?

jakarta-ee - Java EE : when Users exceed the number that defined in connection Pool

php - mysql如何获取表的外键