Docs 菜单

连接池

在本指南中,您可以学习;了解PyMongo如何使用连接池来管理与MongoDB 部署的连接,以及如何在应用应用程序中配置连接池设置。

连接池是PyMongo维护的打开数据库连接的缓存。 当您的应用程序请求连接到MongoDB时, PyMongo无缝地从池中获取连接,执行操作,然后将连接返回到池中以供重用。

连接池有助于减少应用程序延迟和PyMongo创建新连接的次数。

您可以在 MongoClient对象或连接 URI 中指定以下连接池设置:

设置
说明

connectTimeoutMS

The time that PyMongo waits when establishing a new connection before timing out.

Data Type: int
Default: 20000
MongoClient Example: connectTimeoutMS = 40000
Connection URI Example: connectTimeoutMS=40000

maxConnecting

The maximum number of connections that each pool can establish concurrently. If this limit is reached, further requests wait until a connection is established or another in-use connection is checked back into the pool.

Data Type: int
Default: 2
MongoClient Example: maxConnecting = 3
Connection URI Example: maxConnecting=3

maxIdleTimeMS

The maximum time that a connection can remain idle in the pool. When a connection exceeds this limit, PyMongo closes the connection and removes it from the pool.

Data Type: int
Default: None (no limit)
MongoClient Example: maxIdleTimeMS = 60000
Connection URI Example: maxIdleTimeMS=60000

maxPoolSize

The maximum number of concurrent connections that the pool maintains. If the maximum pool size is reached, further requests wait until a connection becomes available.

Data Type: int
Default: 100
MongoClient Example: maxPoolSize = 150
Connection URI Example: maxPoolSize=150

minPoolSize

The minimum number of concurrent connections that the pool maintains. If the number of open connections falls below this value due to network errors, PyMongo attempts to create new connections to maintain this minimum.

Data Type: int
Default: 0
MongoClient Example: minPoolSize = 3
Connection URI Example: minPoolSize=3

socketTimeoutMS

The length of time that PyMongo waits for a response from the server before timing out.

Data Type: int
Default: None (no timeout)
MongoClient Example: socketTimeoutMS = 100000
Connection URI Example: socketTimeoutMS=100000

waitQueueTimeoutMS

How long a thread waits for a connection to become available in the connection pool before timing out.

Data Type: int
Default: None (no timeout)
MongoClient Example: waitQueueTimeoutMS = 100000
Connection URI Example: waitQueueTimeoutMS=100000

以下代码使用 maxPoolSize 参数创建最大连接池大小为 50 的客户端:

client = MongoClient(host, port, maxPoolSize=50)

以下代码创建一个配置与前面的示例相同的客户端,但使用了连接 URI:

client = MongoClient("mongodb://<host>:<port>/?maxPoolSize=50")

要学习;了解有关连接池的更多信息,请参阅MongoDB Server手册中的 连接池概述。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: