使用 SDK 的 Amazon SQS 示例 JavaScript V3 - Amazon SDK for JavaScript
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

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

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

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

使用 SDK 的 Amazon SQS 示例 JavaScript V3

以下代码示例向您展示如何通过使用Amazon SDK for JavaScript通过 Amazon SQS 进行。

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

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

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

主题

操作

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

适用于的开 JavaScript V3

创建客户端。

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

更改 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

创建客户端。

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 { var visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 20, // 20 second timeout }; const results = await sqsClient.send( new ChangeMessageVisibilityCommand(params) ); 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

接收 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

创建客户端。

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

创建 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

创建客户端。

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

接收和删除 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

创建客户端。

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

删除 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

创建客户端。

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

获取 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

创建客户端。

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

列出 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

创建客户端。

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();
适用于的 SDK JavaScript V2

使用长轮询支持接收来自 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

创建客户端。

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();
适用于的 SDK JavaScript V2

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