FAQ

On this page

Frequently Asked Questions

Setting背景
Description描述
connectTimeoutMS

connectTimeoutMS is a connection option that sets the time, in milliseconds, for an individual connection from your connection pool to establish a TCP connection to the MongoDB server before timing out.connectTimeoutMS是一个连接选项,用于设置连接池中的单个连接在超时之前建立到MongoDB服务器的TCP连接的时间(以毫秒为单位)。

Tip

To modify the allowed time for MongoClient.connect to establish a connection to a MongoDB server, use the serverSelectionTimeoutMS option instead.要修改MongoClient.connect的允许时间以建立与MongoDB服务器的连接,请改用serverSelectionTimeoutMS选项。

Default:默认值: 10000

socketTimeoutMS
socketTimeoutMS specifies the amount of time the driver waits for an inactive socket before closing it. 指定驱动程序在关闭非活动套接字之前等待该套接字的时间。The default value is to never time out the socket. 默认值是从不超时套接字。This option applies only to sockets that have already been connected.此选项仅适用于已连接的套接字。
maxTimeMS
maxTimeMS is the maximum amount of time the server should wait for an operation to complete after it has reached the server. 是服务器到达服务器后等待操作完成的最长时间。If an operation runs over the specified time limit, it returns a timeout error.如果操作超过指定的时间限制,则返回超时错误。

To specify the optional settings for your MongoClient, declare one or more available settings in the options object of the constructor as follows:要指定MongoClient的可选设置,请在构造函数的options对象中声明一个或多个可用设置,如下所示:

const client = new MongoClient(uri, {
  connectTimeoutMS: <integer value>,
  socketTimeoutMS: <integer value>
});

To see all the available settings, see the MongoClientOptions API Documentation.要查看所有可用设置,请参阅MongoClient API文档

To prevent the driver from hanging during connection or to prevent the driver from spending too long trying to reach unreachable replica sets, you can set the connectTimeoutMS option of your connection options. 要防止驱动程序在连接过程中挂起,或防止驱动程序花费太长时间尝试访问无法访问的副本集,可以设置连接选项connectTimeoutMS选项。Generally, you should ensure that the connectTimeoutMS setting is not lower than the longest network latency you have to a member of the set. 通常,您应该确保connectTimeoutMS设置不低于您对集合成员的最长网络延迟。If one of the secondary members is on the other side of the planet and has a latency of 10000 milliseconds, setting the connectTimeoutMS to anything lower will prevent the driver from ever connecting to that member.如果其中一个辅助成员位于地球的另一端,且延迟为10000毫秒,则将connectTimeoutMS设置为任何更低的值都将阻止驱动程序连接到该成员。

No, you should not use socketTimeoutMS to end operations that may run for too long and slow down the application. 您不应该使用socketTimeoutMS来结束可能运行太长时间的操作并降低应用程序的速度。Attempting to do so may not achieve the intended result.不,试图这样做可能无法达到预期的结果。

Closing the socket causes a reconnect of the driver's connection pool, introducing latency to any other queued up operations. 关闭套接字会导致重新连接驱动程序的连接池,从而导致任何其他排队操作的延迟。Chronically slow operations will, therefore, cause a large number of reconnect requests, negatively impacting throughput and performance.因此,长期缓慢的操作将导致大量重新连接请求,对吞吐量和性能产生负面影响。

Also, closing the socket does not terminate the operation; it will continue to run on the MongoDB server, which could cause data inconsistencies if the application retries the operation on failure.此外,关闭插座不会终止操作;它将继续在MongoDB服务器上运行,如果应用程序在失败时重试该操作,可能会导致数据不一致。

However, there are important use cases for socketTimeoutMS - consider the following cases:但是,对于socketTimeoutMS有重要的使用案例——考虑以下情况:

  • A MongoDB process erroring outMongoDB进程出错
  • A misconfigured firewall causing a socket connection without sending a FIN packet配置错误的防火墙导致套接字连接而不发送FIN数据包

In those cases, there is no way to detect that the connection has died. 在这些情况下,无法检测连接是否已断开。Setting the socketTimeoutMS is essential to ensure that the sockets are closed correctly. 设置socketTimeoutMS对于确保插座正确关闭至关重要。A good rule of thumb is to set socketTimeoutMS to two to three times the length of the slowest operation that runs through the driver.一个好的经验法则是将socketTimeoutMS设置为通过驱动程序运行的最慢操作长度的两到三倍。

Having a large connection pool does not always reduce reconnection requests. 拥有大型连接池并不总是能够减少重新连接请求。Consider the following example:考虑下面的例子:

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毫秒内执行某些操作以避免关闭。

One message every 3000 milliseconds is not enough to keep the sockets active, so several of the sockets will time out after 5000 milliseconds. 每3000毫秒发送一条消息不足以使套接字保持活动状态,因此有几个套接字将在5000毫秒后超时。Reduce the poolSize in the connection settings to fix the problem.减少连接设置中的poolSize以修复此问题。

To specify the optional poolSize setting for your MongoClient, declare it in the options object of the constructor as follows:要为MongoClient指定可选的poolSize设置,请在构造函数的options对象中声明它,如下所示:

const client = new MongoClient(uri, {
  poolSize: <integervalue>,
});

If you set the value of connectTimeoutMS or socketTimeoutMS to 0, your application will use the operating system's default socket timeout value.如果将connectTimeoutMSsocketTimeoutMS的值设置为0,则应用程序将使用操作系统的默认套接字超时值。

You can prevent long-running operations from slowing down the server by specifying a timeout value. 通过指定超时值,可以防止长时间运行的操作降低服务器速度。You can use the maxTimeMS option setting in your MongoClient constructor to apply this to all the operations called by the client, or chain the maxTimeMS() method to an operation that returns a Cursor to apply to that specific one.您可以使用MongoClient构造函数中的maxTimeMS选项设置将其应用于客户端调用的所有操作,或者将maxTimeMS()方法链接到一个操作,该操作返回一个光标以应用于该特定操作。

To specify the optional maxTimeMS setting for your MongoClient, declare it in the options object of the constructor as follows:要为MongoClient指定可选的maxTimeMS设置,请在构造函数的options对象中声明它,如下所示:

const client = new MongoClient(uri, {
  connectTimeoutMS: <integer value>,
  socketTimeoutMS: <integer value>,
  maxTimeMS: <integer value>,
});

The following example shows how you can chain the maxTimeMS() method to an operation that returns a Cursor:以下示例显示如何将maxTimeMS()方法链接到返回Cursor的操作:

// Execute a find command
await collection
  .find({ $where: "sleep(100) || true" })
  .maxTimeMS(50)
  .count((err, count) => {});

keepAlive is a connection-setting that sets the number of milliseconds to wait before initiating a TLS keepAlive on a TCP Socket. keepAlive是一种connection-setting,用于设置在TCP套接字上启动TLS keepAlive之前等待的毫秒数。The keepAlive option will keep a socket alive by sending periodic probes to MongoDB. keepAlive选项将通过定期向MongoDB发送探测来保持套接字的活动状态。However, this only works if the operating system supports SO_KEEPALIVE .但是,这只有在操作系统支持SO_KEEPALIVE时才有效。

Warning
If a firewall ignores or drops the keepAlive packets this may not work如果防火墙忽略或丢弃keepAlive数据包,这可能不起作用

Internal firewalls that exist between application servers and MongoDB are often misconfigured and are overly aggressive in their removal of socket connections.存在于应用服务器和MongoDB之间的内部防火墙通常配置错误,并且在移除套接字连接时过于激进。

If you experience unexpected network behavior, here are some things to check:如果您遇到意外的网络行为,请检查以下事项:

  1. The firewall should send a FIN packet when closing a socket,allowing the driver to detect that the socket is closed.防火墙应在关闭套接字时发送FIN数据包,使驱动程序能够检测到套接字已关闭。
  2. The firewall should allow keepAlive probes.防火墙应允许keepAlive探测。

In most operating systems, each connection is associated with a file descriptor. 在大多数操作系统中,每个连接都与一个文件描述符相关联。There is typically a limit set by the operating system on the number of file descriptors used by a single process. 操作系统通常会对单个进程使用的文件描述符的数量设置限制。An ECONNRESET error can occur if the connection pool size surpasses the limit of file descriptors.如果连接池大小超过file descriptors的限制,则可能发生ECONNRESET错误。

Consider the following operation:考虑以下操作:

1const uri = "mongodb://localhost:27017/test?maxPoolSize=5000";
2// create a new MongoClient
3const client = new MongoClient(uri);
4
5await client.connect(err=> { 6 // connection 7});

If this operation causes an ECONNRESET error, you may have run into the file descriptor limit for your Node.js process. 如果此操作导致ECONNRESET错误,则您可能遇到Node.js进程的file descriptor限制。In that case you must increase the number of file descriptors for the Node.js process. <在这种情况下,必须增加Node.js进程的文件描述符数量。/ins>On MacOS and Linux you do this with the ulimit shell command.在MacOS和Linux上,可以使用ulimit shell命令执行此操作。

ulimit -n 6000

This sets the maximum number of file descriptors for the process to 6000, allowing Node.js to connect with a pool size of 5000 sockets.这将进程的最大file descriptors数设置为6000,允许Node.js连接5000个套接字大小的池。

A slow operation may delay your other operations that occur after it, if the poolSize has not been set in the connection options. 如果未在连接选项中设置poolSize,则慢速操作可能会延迟之后发生的其他操作。MongoDB is synchronous and uses a single execution thread per socket, meaning that MongoDB will execute one single operation per socket at any point in time. MongoDB是同步的,每个套接字使用一个执行线程,这意味着MongoDB将在任何时间点对每个套接字执行一个操作。Any other operation sent to that socket will have to wait until the current operation is finished. 发送到该套接字的任何其他操作都必须等待当前操作完成。If you have a slow-running operation that holds up other operations, the best solution is to create a separate connection pool for the slow operation, isolating it from other, faster operations.如果您有一个运行缓慢的操作会阻塞其他操作,那么最好的解决方案是为该慢操作创建一个单独的连接池,将其与其他更快的操作隔离开来。

Note

If the number of operations is greater than the set poolSize and a slow operation occurs, subsequent operations will be delayed.如果操作数大于设置的poolSize且操作速度较慢,则后续操作将延迟。

To create a separate connection pool, instantiate another MongoClient call the connect() method on it. 要创建单独的连接池,请实例化另一个MongoClient调用其上的connect()方法。See the following example for the syntax you can use to create two clients, each with its own connection pool:有关可用于创建两个客户端(每个客户端都有自己的连接池)的语法,请参阅以下示例:

const clientA = new MongoClient(uri, options);
clientA.connect(); // any method calls on clientA use clientA's connection pool对clientA的任何方法调用都使用clientA的连接池
const clientB = new MongoClient(uri, options); clientB.connect(); // any method calls on clientB use clientB's connection pool对clientB的任何方法调用都使用clientB的连接池

The connection string passed to the driver must use exact hostnames for the servers as set in the Replica Set Config. 传递给驱动程序的连接字符串必须使用副本集配置中设置的服务器的确切主机名。Given the following configuration settings for your Replica Set, in order for the Replica Set discovery and failover to work the driver should be able to reach server1, server2, and server3.给定副本集的以下配置设置,为了使副本集发现和故障切换工作,驱动程序应该能够访问server1server2server3

{
  "_id": "testSet",
  "version": 1,
  "protocolVersion": 1,
  "members": [
    {
      "_id": 1,
      "host": "server1:31000"
    },
    {
      "_id": 2,
      "host": "server2:31001"
    },
    {
      "_id": 3,
      "host": "server3:31002"
    }
  ]
}

If you are unable to find the answer to your question here, try our forums and support channels listed in the Issues and Help section.如果您无法在此处找到问题的答案,请尝试问题和帮助部分列出的论坛和支持渠道。