

适用于 JavaScript 的 AWS SDK v2 已终止支持。建议您迁移到 [适用于 JavaScript 的 AWS SDK v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/)。有关更多详情和如何迁移的信息，请参阅本[公告](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)。

# 在 Node.js 中重复使用具有保持连接功能的连接
<a name="node-reusing-connections"></a>

默认情况下，默认的 Node.js HTTP/HTTPS 代理会为每个新请求创建一个新的 TCP 连接。为了节省建立新连接的成本，您可以重复使用现有的连接。

对于短期操作（如 DynamoDB 查询），设置 TCP 连接的延迟开销可能大于操作本身。此外，由于 DynamoDB [静态加密](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/encryption.howitworks.html)已与 [AWS KMS](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/encryption.howitworks.html) 集成，您可能会遇到延迟，因为数据库必须为每个操作重新建立新的 AWS KMS 缓存条目。

配置 SDK for JavaScript 以重复使用 TCP 连接的最简单方法是将 ` AWS_NODEJS_CONNECTION_REUSE_ENABLED` 环境变量设置为 `1`。[2.463.0](https://github.com/aws/aws-sdk-js/blob/master/CHANGELOG.md#24630) 版本中已添加此功能。

或者，您可以将 HTTP 或 HTTPS 代理的 `keepAlive` 属性设置为 `true`，如以下示例所示。

```
const AWS = require('aws-sdk');
// http or https
const http = require('http');
const agent = new http.Agent({
  keepAlive: true, 
// Infinity is read as 50 sockets
  maxSockets: Infinity
});

AWS.config.update({
  httpOptions: {
    agent
  }
});
```

以下示例演示了如何仅为 DynamoDB 客户端设置 `keepAlive`：

```
const AWS = require('aws-sdk')
// http or https
const https = require('https');
const agent = new https.Agent({
  keepAlive: true
});

const dynamodb = new AWS.DynamoDB({
  httpOptions: {
    agent
  }
});
```

如果已启用 `keepAlive`，您还可以使用 `keepAliveMsecs` 设置 TCP Keep-Alive 数据包的初始延迟，默认值为 1000ms。有关详细信息，请参阅 [Node.js 文档](https://nodejs.org/api/http.html)。