简体   繁体   English

什么是应用程序中的连接池?

[英]What is connection pooling in an application?

A framework or an application automatically connect the database and we have to just use the database object for DB related operation. 框架或应用程序会自动连接数据库,而我们只需要使用数据库对象来进行与数据库相关的操作。 In CMS or framework, a term "connection pooling" is very popular. 在CMS或框架中,术语“连接池”非常流行。 You can opt CMS or framework of PHP. 您可以选择CMS或PHP框架。

  • What is connection pooling? 什么是连接池?
  • Can someone describe this with an example? 有人可以举例说明吗?
  • What is the advantage of connection pooling? 连接池的优点是什么?

Without connection pooling: 没有连接池:

Every time you want to talk to the database, you have to open a connection, use it, then close it again. 每次要与数据库对话时,都必须打开一个连接,使用它,然后再次关闭它。

With connection pooling: 使用连接池:

The connections are kept open all the time (in a pool). 连接始终保持打开状态(在池中)。 When you want to talk to the database, you take an already connection, that isn't already in a use, use it, then put it back. 当您想与数据库对话时,您需要建立一个已经没有使用的连接,使用它,然后再放回去。

This is more efficient then opening and closing them all the time. 这样会比始终打开和关闭它们更有效。

Connection pooling generally refers to, well, having a pool of connections which is being reused. 连接池通常指的是具有正在重用的连接池。 To contrast this with non-pooled connections: typically every program instance connects to the database by itself every time it is run. 将此与非池化连接进行对比:通常,每个程序实例每次运行时都自行连接到数据库。 In a PHP program, you just have the line $db = new PDO(...) , which connects to the database. 在PHP程序中,只有$db = new PDO(...) ,它连接到数据库。 If you have 100 simultaneous visitors, 100 separate instances of that script will be run simultaneously, and 100 separate connections will be established to the database simultaneously. 如果您有100个同时访问者,则将同时运行该脚本的100个独立实例,并同时建立与数据库的100个独立连接。 This may be very inefficient and/or temporarily overwhelm the database server. 这可能效率很低和/或暂时使数据库服务器不堪重负。

A connection pool works by establishing, say, 50 permanent connections to the database which stay open the whole time. 连接池通过建立与数据库的50个永久连接(这些连接始终保持打开状态)来工作。 A PHP script would then simply pick one of these open connections to talk to the database and drop it back into the pool when it's done. 然后,PHP脚本只需选择这些打开的连接之一即可与数据库进行对话,并在完成后将其放回池中。 If suddenly more than 50 PHP scripts try to use connections from this pool at once, the first 50 will succeed, and the rest will have to wait in line until an unused connection becomes available. 如果突然有超过50个PHP脚本尝试一次使用该池中的连接,则前50个将成功,其余的将不得不排队等待直到未使用的连接变为可用。 This is more efficient, because connections aren't opened and torn down all the time, and it doesn't overwhelm the database server when sudden spikes occur. 这是更有效的,因为连接不会一直打开和断开,并且在突然出现峰值时也不会使数据库服务器不堪重负。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM