Amazon SQS 示例 JavaScript V3 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Amazon SQS 示例 JavaScript V3

以下代码示例显示如何使用AWS SDK for JavaScriptV3 和 AAmazon SQS。

操作代码节选,展示如何调用具体的 Amazon SQS 函数。

方案展示如何通过调用多个 Amazon SQS 函数来完成特定任务的代码示例。

每个示例都包含一个指向以下内容的链接 GitHub其中包含了有关如何在上下文中设置和运行代码的说明。

主题

操作

以下代码示例显示如何更改 Amazon SQS 队列等待消息到达的时间。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

更改 Amazon SQS 队列等待消息到达的时间。

// Import required AWS SDK clients and commands for Node.js import { SetQueueAttributesCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, QueueUrl: "SQS_QUEUE_URL", //SQS_QUEUE_URL; e.g., 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' }; const run = async () => { try { const data = await sqsClient.send(new SetQueueAttributesCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.error(err, err.stack); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

更改 Amazon SQS 队列等待消息到达的时间。

// 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); } });

以下代码示例显示如何更改 Amazon SQS 消息超时可见性。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

接收 Amazon SQS 消息并更改其超时可见性。

// Import required AWS SDK clients and commands for Node.js import { ReceiveMessageCommand, ChangeMessageVisibilityCommand, } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const queueURL = "https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME"; // REGION, ACCOUNT_ID, QUEUE_NAME const params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueURL, }; const run = async () => { try { const data = await sqsClient.send(new ReceiveMessageCommand(params)); if (data.Messages != null) { try { const visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 20, // 20 second timeout }; const results = await sqsClient.send( new ChangeMessageVisibilityCommand(visibilityParams) ); console.log("Timeout Changed", results); } catch (err) { console.log("Delete Error", err); } } else { console.log("No messages to change"); } return data; // For unit tests. } catch (err) { console.log("Receive Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

接收 Amazon SQS 消息并更改其超时可见性。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk') // Set the region to us-west-2 AWS.config.update({ region: 'us-west-2' }) // Create the SQS service object var sqs = new AWS.SQS({ apiVersion: '2012-11-05' }) var queueURL = 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' var params = { AttributeNames: ['SentTimestamp'], MaxNumberOfMessages: 1, MessageAttributeNames: ['All'], QueueUrl: queueURL } sqs.receiveMessage(params, function (err, data) { if (err) { console.log('Receive Error', err) } else { // Make sure we have a message if (data.Messages != null) { var visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 20 // 20 second timeout } sqs.changeMessageVisibility(visibilityParams, function (err, data) { if (err) { console.log('Delete Error', err) } else { console.log('Timeout Changed', data) } }) } else { console.log('No messages to change') } } })

以下代码示例显示如何创建 Amazon SQS 队列。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

创建 Amazon SQS 标准队列。

// Import required AWS SDK clients and commands for Node.js import { CreateQueueCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { QueueName: "SQS_QUEUE_NAME", //SQS_QUEUE_URL Attributes: { DelaySeconds: "60", // Number of seconds delay. MessageRetentionPeriod: "86400", // Number of seconds delay. }, }; const run = async () => { try { const data = await sqsClient.send(new CreateQueueCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

创建等待消息到达的 Amazon SQS 队列。

// Import required AWS SDK clients and commands for Node.js import { CreateQueueCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { QueueName: "SQS_QUEUE_NAME", //SQS_QUEUE_URL; e.g., 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, }; const run = async () => { try { const data = await sqsClient.send(new CreateQueueCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.error(err, err.stack); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建 Amazon SQS 标准队列。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create an SQS service object var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var params = { QueueName: 'SQS_QUEUE_NAME', Attributes: { 'DelaySeconds': '60', 'MessageRetentionPeriod': '86400' } }; sqs.createQueue(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrl); } });

创建等待消息到达的 Amazon SQS 队列。

// 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); } });

以下代码示例显示如何从 Amazon SQS 队列中删除消息。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

接收和删除 Amazon SQS 消息。

// Import required AWS SDK clients and commands for Node.js import { ReceiveMessageCommand, DeleteMessageCommand, } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const queueURL = "SQS_QUEUE_URL"; //SQS_QUEUE_URL; e.g., 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' const params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], QueueUrl: queueURL, VisibilityTimeout: 20, WaitTimeSeconds: 0, }; const run = async () => { try { const data = await sqsClient.send(new ReceiveMessageCommand(params)); if (data.Messages) { var deleteParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, }; try { const data = await sqsClient.send(new DeleteMessageCommand(deleteParams)); console.log("Message deleted", data); } catch (err) { console.log("Error", err); } } else { console.log("No messages to delete"); } return data; // For unit tests. } catch (err) { console.log("Receive Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

接收和删除 Amazon SQS 消息。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create an SQS service object var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var queueURL = "SQS_QUEUE_URL"; var params = { AttributeNames: [ "SentTimestamp" ], MaxNumberOfMessages: 10, MessageAttributeNames: [ "All" ], QueueUrl: queueURL, VisibilityTimeout: 20, WaitTimeSeconds: 0 }; sqs.receiveMessage(params, function(err, data) { if (err) { console.log("Receive Error", err); } else if (data.Messages) { var deleteParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle }; sqs.deleteMessage(deleteParams, function(err, data) { if (err) { console.log("Delete Error", err); } else { console.log("Message Deleted", data); } }); } });

以下代码示例显示如何删除 Amazon SQS 队列。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

删除 Amazon SQS 队列。

// Import required AWS SDK clients and commands for Node.js import { DeleteQueueCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { QueueUrl: "SQS_QUEUE_URL" }; //SQS_QUEUE_URL e.g., 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' const run = async () => { try { const data = await sqsClient.send(new DeleteQueueCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.error(err, err.stack); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

删除 Amazon SQS 队列。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create an SQS service object var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var params = { QueueUrl: 'SQS_QUEUE_URL' }; sqs.deleteQueue(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何获取 Amazon SQS 队列的 URL。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

获取Amazon SQS 队列的 URL。

// Import required AWS SDK clients and commands for Node.js import { GetQueueUrlCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { QueueName: "SQS_QUEUE_NAME" }; const run = async () => { try { const data = await sqsClient.send(new GetQueueUrlCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

获取Amazon SQS 队列的 URL。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create an SQS service object var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var params = { QueueName: 'SQS_QUEUE_NAME' }; sqs.getQueueUrl(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrl); } });

以下代码示例显示如何列出 Amazon SQS 队列。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

列出您的Amazon SQS 队列。

// Import required AWS SDK clients and commands for Node.js import { ListQueuesCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; const run = async () => { try { const data = await sqsClient.send(new ListQueuesCommand({})); console.log("Success", data); return data; // For unit tests. } catch (err) { console.error(err, err.stack); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

列出您的Amazon SQS 队列。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create an SQS service object var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var params = {}; sqs.listQueues(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrls); } });

以下代码示例显示如何从 Amazon SQS 队列接收消息。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

使用长轮询支持从 Amazon SQS 队列接收消息。

// Import required AWS SDK clients and commands for Node.js import { ReceiveMessageCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const queueURL = "SQS_QUEUE_URL"; // SQS_QUEUE_URL const params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueURL, WaitTimeSeconds: 20, }; const run = async () => { try { const data = await sqsClient.send(new ReceiveMessageCommand(params)); console.log("Success, ", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

使用长轮询支持从 Amazon SQS 队列接收消息。

// 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); } });

以下代码示例显示如何将消息发送至 Amazon SQS 队列。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };

向 Amazon SQS 队列。

// Import required AWS SDK clients and commands for Node.js import { SendMessageCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", // MessageDeduplicationId: "TheWhistler", // Required for FIFO queues // MessageGroupId: "Group1", // Required for FIFO queues QueueUrl: "SQS_QUEUE_URL" //SQS_QUEUE_URL; e.g., 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' }; const run = async () => { try { const data = await sqsClient.send(new SendMessageCommand(params)); console.log("Success, message sent. MessageID:", data.MessageId); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

向 Amazon SQS 队列。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create an SQS service object var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var params = { // Remove DelaySeconds parameter and value for FIFO queues DelaySeconds: 10, MessageAttributes: { "Title": { DataType: "String", StringValue: "The Whistler" }, "Author": { DataType: "String", StringValue: "John Grisham" }, "WeeksOn": { DataType: "Number", StringValue: "6" } }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", // MessageDeduplicationId: "TheWhistler", // Required for FIFO queues // MessageGroupId: "Group1", // Required for FIFO queues QueueUrl: "SQS_QUEUE_URL" }; sqs.sendMessage(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.MessageId); } });