

适用于 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/)。

# 在 Amazon SQS 中启用长轮询
<a name="sqs-examples-enable-long-polling"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**此 Node.js 代码示例演示：**
+ 如何为新创建的队列启用长轮询
+ 如何为现有队列启用长轮询
+ 如何在收到消息时启用长轮询

## 情景
<a name="sqs-examples-enable-long-polling-scenario"></a>

长轮询使 Amazon SQS 在发送响应之前等待指定的时间，以便消息在队列中变得可用，从而减少空响应的数量。此外，长轮询通过查询所有服务器而不是执行服务器采样，消除了假的空响应。要启用长轮询，您必须为接收的消息指定非零等待时间。为此，您可以设置队列的 `ReceiveMessageWaitTimeSeconds` 参数或者设置在收到消息时的 `WaitTimeSeconds` 参数。

在本示例中，使用了一系列 Node.js 模块来启用长轮询。这些 Node.js 模块使用 SDK for JavaScript，通过 `AWS.SQS` 客户端类的以下方法来启用长轮询：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#setQueueAttributes-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#setQueueAttributes-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#receiveMessage-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#receiveMessage-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#createQueue-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#createQueue-property)

有关 Amazon SQS 长轮询的更多信息，请参阅《Amazon Simple Queue Service Developer Guide》**中的 [Long Polling](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html)。

## 先决条件任务
<a name="sqs-examples-enable-long-polling-prerequisites"></a>

要设置和运行此示例，您必须先完成以下任务：
+ 安装 Node.js。有关安装 Node.js 的更多信息，请参阅 [Node.js 网站](https://nodejs.org)。
+ 使用用户凭证创建共享配置文件。有关提供共享凭证文件的更多信息，请参阅[从共享凭证文件加载 Node.js 中的凭证](loading-node-credentials-shared.md)。

## 创建队列时启用长轮询
<a name="sqs-examples-enable-long-polling-on-queue-creation"></a>

创建文件名为 `sqs_longpolling_createqueue.js` 的 Node.js 模块。请确保按前面所示配置开发工具包。要访问 Amazon SQS，请创建 `AWS.SQS` 服务对象。创建一个包含创建队列所需的参数的 JSON 对象，其中包括 `ReceiveMessageWaitTimeSeconds` 参数的非零值。调用 `createQueue` 方法。接下来为队列启用长轮询。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueName: "SQS_QUEUE_NAME",
  Attributes: {
    ReceiveMessageWaitTimeSeconds: "20",
  },
};

sqs.createQueue(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrl);
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node sqs_longpolling_createqueue.js
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_longpolling_createqueue.js)找到。

## 在现有队列上启用长轮询
<a name="sqs-examples-enable-long-polling-existing-queue"></a>

创建文件名为 `sqs_longpolling_existingqueue.js` 的 Node.js 模块。请确保按前面所示配置开发工具包。要访问 Amazon Simple Queue Service，请创建一个 `AWS.SQS` 服务对象。创建一个包含设置队列属性所需的参数的 JSON 对象，其中包括 `ReceiveMessageWaitTimeSeconds` 参数的非零值和队列的 URL。调用 `setQueueAttributes` 方法。接下来为队列启用长轮询。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  Attributes: {
    ReceiveMessageWaitTimeSeconds: "20",
  },
  QueueUrl: "SQS_QUEUE_URL",
};

sqs.setQueueAttributes(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node sqs_longpolling_existingqueue.js
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_longpolling_existingqueue.js)找到。

## 在接收消息时启用长轮询
<a name="sqs-examples-enable-long-polling-on-receive-message"></a>

创建文件名为 `sqs_longpolling_receivemessage.js` 的 Node.js 模块。请确保按前面所示配置开发工具包。要访问 Amazon Simple Queue Service，请创建一个 `AWS.SQS` 服务对象。创建一个包含接收消息所需的参数的 JSON 对象，其中包括 `WaitTimeSeconds` 参数的非零值和队列的 URL。调用 `receiveMessage` 方法。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var queueURL = "SQS_QUEUE_URL";

var params = {
  AttributeNames: ["SentTimestamp"],
  MaxNumberOfMessages: 1,
  MessageAttributeNames: ["All"],
  QueueUrl: queueURL,
  WaitTimeSeconds: 20,
};

sqs.receiveMessage(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node sqs_longpolling_receivemessage.js
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_longpolling_receivemessage.js)找到。