rt
Docs Home / Node.js Driver / Connect / Connection Options

Manage Connections with Connection Pools使用连接池管理连接

Overview概述

In this guide, you can learn about how Node.js driver uses connection pools to manage connections to a MongoDB deployment and how you can configure connection pool settings in your application.在本指南中,您可以了解Node.js驱动程序如何使用连接池来管理到MongoDB部署的连接,以及如何在应用程序中配置连接池设置。

A connection pool is a cache of open database connections maintained by Node.js driver. When your application requests a connection to MongoDB, Node.js driver seamlessly gets a connection from the pool, performs operations, and returns the connection to the pool for reuse.连接池是Node.js驱动程序维护的开放数据库连接的缓存。当你的应用程序请求连接到MongoDB时,Node.js驱动程序会无缝地从池中获取连接,执行操作,并将连接返回到池中以供重用。

Connection pools help reduce application latency and the number of times new connections are created by Node.js driver.连接池有助于减少应用程序延迟和Node.js驱动程序创建新连接的次数。

Configure Connection Pools配置连接池

Every MongoClient instance has a built-in connection pool for each server in your MongoDB topology. If you do not configure the minPoolSize option, connection pools open sockets on demand to support concurrent requests to MongoDB in your application.每个MongoClient实例都有一个内置的连接池,用于MongoDB拓扑中的每个服务器。如果不配置minPoolSize选项,连接池会按需打开套接字,以支持应用程序中对MongoDB的并发请求。

You can specify the following connection pool settings in your MongoClient instance:您可以在MongoClient实例中指定以下连接池设置:

Setting设置Description描述
maxPoolSizeThe maximum number of concurrent connections that the pool maintains. If the number of in-use connections to a server reaches the specified value, the next request to that server waits until a connection becomes available.池维护的最大并发连接数。如果到服务器的正在使用的连接数达到指定值,则对该服务器的下一个请求将等待,直到连接可用。
Default: 默认值:100
maxConnectingThe maximum number of connections that each pool can establish concurrently.每个池可以同时建立的最大连接数。
minPoolSizeThe minimum number of concurrent connections that the pool maintains.池维护的最小并发连接数。
Default: 默认值:0
maxIdleTimeMSThe maximum number of milliseconds that a connection can remain idle in the pool.连接在池中可以保持空闲的最大毫秒数。
Default: 默认值:0 (no limit)(无限制)
waitQueueTimeoutMSThe maximum number of milliseconds that a request can wait for a socket to become available.请求可以等待套接字可用的最大毫秒数。
Default: 默认值:0 (no limit)(无限制)

maxPoolSize

In addition to the sockets needed to support your application's requests, each MongoClient instance opens up to two connections per server in your MongoDB topology for monitoring the server's state.除了支持应用程序请求所需的套接字外,每个MongoClient实例在MongoDB拓扑中每个服务器最多打开两个连接,用于监控服务器的状态。

For example, a client connected to a three-node replica set opens six monitoring sockets. 例如,连接到三节点副本集的客户端打开六个监控套接字。If the application uses the default setting for maxPoolSize and only queries the primary (default) node, then there can be at most 106 open sockets and 100 connections in the connection pool. 如果应用程序使用maxPoolSize的默认设置并且只查询主(默认)节点,则连接池中最多只能有106个打开的套接字和100个连接。If the application uses a read preference to query the secondary nodes, those connection pools grow and there can be 306 total connections including the open monitoring sockets.如果应用程序使用读取首选项来查询辅助节点,则这些连接池会增长,包括打开的监控套接字在内,总共有306个连接。

To support high numbers of concurrent MongoDB requests within one process, you can increase maxPoolSize.为了在一个进程中支持大量并发MongoDB请求,您可以增加maxPoolSize

The following code creates a MongoClient instance with a maximum connection pool size of 200 by specifying the maxPoolSize option in the options object:以下代码通过在options对象中指定maxPoolSize选项,创建了一个最大连接池大小为200MongoClient实例:

const { MongoClient } = require('mongodb');

const uri = '<connection-string>';
const client = new MongoClient(uri, {
maxPoolSize: 200
});

maxConnecting

Connection pools rate-limit connection establishment. The maxConnecting option determines the number of connections that the pool can create in parallel at any time. 连接池速率限制连接建立。maxConnecting选项决定池在任何时候可以并行创建的连接数。For example, if the value of maxConnecting is 2, the third request that attempts to concurrently check out a connection succeeds only when one the following cases occurs:例如,如果maxConnecting的值为2,则尝试并发签出连接的第三个请求仅在发生以下情况之一时成功:

  • The connection pool finishes creating a connection and there are fewer than maxPoolSize connections in the pool.连接池已完成创建连接,池中的连接数小于maxPoolSize
  • An existing connection is checked back into the pool.将现有连接检回池中。

The following code creates a MongoClient instance with a maximum number of 2 connections to be established concurrently per pool by specifying the maxConnecting option in the options object:以下代码通过在options对象中指定maxConnecting选项,创建了一个MongoClient实例,每个池最多可同时建立2个连接:

const { MongoClient } = require('mongodb');

const uri = '<connection-string>';
const client = new MongoClient(uri, {
maxConnecting: 2
});

minPoolSize

You can set the minimum number of connections to each server with the minPoolSize option. The driver ensures that there are always at least the number of connections set by the minPoolSize option in the connection pool. 您可以使用minPoolSize选项设置每个服务器的最小连接数。驱动程序确保连接池中始终至少有minPoolSize选项设置的连接数。If sockets are closed, causing the total number of sockets (both in use and idle) to drop below the minimum, more sockets are opened until the minimum is reached.如果套接字关闭,导致套接字总数(使用中和空闲)降至最低值以下,则会打开更多套接字,直到达到最低值。

The following code creates a MongoClient instance with a minimum connnection pool size of 10 by specifying the minPoolSize option in the options object:以下代码通过在options对象中指定minPoolSize选项,创建了一个最小连接池大小为10MongoClient实例:

const { MongoClient } = require('mongodb');

const uri = '<connection-string>';
const client = new MongoClient(uri, {
minPoolSize: 10
});

Note

A MongoClient configured with maxIdleTimeMS and minPoolSize set to 0 is optimal for workloads with sustained periods of low activity. This configuration allows the connection pool to close unused connections during periods of inactivity.配置了maxIdleTimeMSminPoolSize设置为0MongoClient最适合持续低活动的工作负载。此配置允许连接池在不活动期间关闭未使用的连接。

In versions earlier than 6.18.0, the Node.js driver did not close idle connections when minPoolSize was set to 0 during periods of inactivity. 在6.18.0之前的版本中,当minPoolSize在非活动期间设置为0时,Node.js驱动程序不会关闭空闲连接。Starting in version 6.18.0, the connection pool correctly closes idle connections regardless of the minPoolSize setting.从版本6.18.0开始,无论minPoolSize设置如何,连接池都会正确关闭空闲连接。

maxIdleTimeMS

You can set the maximum number of milliseconds that a connection can remain idle in the pool by setting the maxIdleTimeMS option. Once a connection has been idle for maxIdleTimeMS, the connection pool removes and replaces it. This option defaults to 0 (no limit).通过设置maxIdleTimeMS选项,可以设置连接在池中保持空闲的最大毫秒数。一旦连接在maxIdleTimeMS中处于空闲状态,连接池就会删除并替换它。此选项默认为0(无限制)。

The following code creates a MongoClient instance with a maximum idle time of 10000 milliseconds (10 seconds) by specifying the maxIdleTimeMS setting in the options object:以下代码通过在options对象中指定maxIdleTimeMS设置,创建了一个最大空闲时间为10000毫秒(10秒)的MongoClient实例:

const { MongoClient } = require('mongodb');

const uri = '<connection-string>';
const client = new MongoClient(uri, {
maxIdleTimeMS: 10000
});

waitQueueTimeoutMS

MongoClient supports multiple concurrent requests. For each process, create a client and reuse it for all operations in a process. This practice is more efficient than creating a client for each request.支持多个并发请求。对于每个流程,创建一个客户端并将其重用于流程中的所有操作。这种做法比为每个请求创建一个客户端更有效。

The driver does not limit the number of requests that can wait for sockets to become available, and it is the application's responsibility to limit the size of its pool to bound queuing during a load spike. Requests wait for the amount of time specified in the waitQueueTimeoutMS option, which defaults to 0 (no limit).驱动程序不限制可以等待套接字可用的请求数量,应用程序有责任在负载高峰期间将其池的大小限制在绑定队列中。请求等待waitQueueTimeoutMS选项中指定的时间,默认为0(无限制)。

A request that waits more than the length of time defined by waitQueueTimeoutMS for a socket raises a connection error. Use this option if it is more important to bound the duration of operations during a load spike than it is to complete every operation.等待时间超过waitQueueTimeoutMS为套接字定义的时间长度的请求会引发连接错误。如果在负载高峰期间限制操作持续时间比完成每个操作更重要,请使用此选项。

The following code creates a MongoClient instance with a maximum wait queue timeout of 10000 milliseconds (10 seconds) by declaring it in the options object:以下代码通过在options对象中声明来创建最大等待队列超时为10000毫秒(10秒)的MongoClient实例:

const { MongoClient } = require('mongodb');

const uri = '<connection-string>';
const client = new MongoClient(uri, {
waitQueueTimeoutMS: 10000
});

Closing Connections关闭连接

When any request calls MongoClient.close(), the Node.js driver performs the following actions:当任何请求调用MongoClient.close()时,Node.js驱动程序将执行以下操作:

  • Closes all idle sockets in the connection pool关闭连接池中的所有空闲套接字
  • Closes all sockets that are in use as they are returned to the pool在将所有正在使用的套接字返回池时将其关闭
  • Closes all sockets that are in use only when the associated operations complete仅当相关操作完成时关闭所有正在使用的套接字

Calling MongoClient.close() closes only inactive sockets and does not directly terminate any ongoing operations.调用MongoClient.close()只关闭非活动套接字,不会直接终止任何正在进行的操作。

Note

The MongoClient.close() method does close existing sessions and transactions, which might indirectly affect the behavior of ongoing operations and open cursors.MongoClient.close()方法确实会关闭现有的会话和事务,这可能会间接影响正在进行的操作和打开游标的行为。

Avoid Socket Timeouts避免套接字超时

Having a large connection pool does not always reduce reconnection requests. Consider the following example scenario:拥有一个大的连接池并不总是能减少重新连接请求。考虑以下示例场景:

  • An application has a connection pool size of 5 sockets and has the socketTimeoutMS option set to 5000 milliseconds.应用程序的连接池大小为5个套接字,并将socketTimeoutMS选项设置为5000毫秒。
  • Operations occur, on average, every 3000 milliseconds, and reconnection requests are frequent.平均每3000毫秒发生一次操作,并且重新连接请求很频繁。
  • Each socket times out after 5000 milliseconds, which means that all sockets must do something during those 5000 milliseconds to avoid closing.每个套接字在5000毫秒后超时,这意味着所有套接字必须在这5000毫秒内做些什么来避免关闭。

In this scenario, each socket times out after 5000 milliseconds, requiring activity within this timeout period to avoid closure. However, one message every 3000 milliseconds isn't enough to keep all sockets active, causing several of them to time out.在这种情况下,每个套接字在5000毫秒后超时,需要在此超时时间内进行活动以避免关闭。然而,每3000毫秒一条消息不足以使所有套接字保持活动状态,导致其中几个套接字超时。

To avoid excessive socket timeouts, reduce the number of connections that the driver can maintain in the connection pool by specifying the maxPoolSize option. To learn how to set the maxPoolSize option, see the maxPoolSize section.为了避免过多的套接字超时,请通过指定maxPoolSize选项来减少驱动程序可以在连接池中维护的连接数。要了解如何设置maxPoolSize选项,请参阅maxPoolSize部分。

API Documentation文档

For more information about creating a MongoClient object with the Node.js driver and specifying options, see the following API documentation:有关使用Node.js驱动程序创建MongoClient对象并指定选项的更多信息,请参阅以下API文档: