与 AWS SDK或DeleteMessage一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

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

与 AWS SDK或DeleteMessage一起使用 CLI

以下代码示例演示如何使用 DeleteMessage

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

从 Amazon SQS 队列接收消息,然后删除该消息。

public static async Task Main() { // If the AWS Region you want to use is different from // the AWS Region defined for the default user, supply // the specify your AWS Region to the client constructor. var client = new AmazonSQSClient(); string queueName = "Example_Queue"; var queueUrl = await GetQueueUrl(client, queueName); Console.WriteLine($"The SQS queue's URL is {queueUrl}"); var response = await ReceiveAndDeleteMessage(client, queueUrl); Console.WriteLine($"Message: {response.Messages[0]}"); } /// <summary> /// Retrieve the queue URL for the queue named in the queueName /// property using the client object. /// </summary> /// <param name="client">The Amazon SQS client used to retrieve the /// queue URL.</param> /// <param name="queueName">A string representing name of the queue /// for which to retrieve the URL.</param> /// <returns>The URL of the queue.</returns> public static async Task<string> GetQueueUrl(IAmazonSQS client, string queueName) { var request = new GetQueueUrlRequest { QueueName = queueName, }; GetQueueUrlResponse response = await client.GetQueueUrlAsync(request); return response.QueueUrl; } /// <summary> /// Retrieves the message from the quque at the URL passed in the /// queueURL parameters using the client. /// </summary> /// <param name="client">The SQS client used to retrieve a message.</param> /// <param name="queueUrl">The URL of the queue from which to retrieve /// a message.</param> /// <returns>The response from the call to ReceiveMessageAsync.</returns> public static async Task<ReceiveMessageResponse> ReceiveAndDeleteMessage(IAmazonSQS client, string queueUrl) { // Receive a single message from the queue. var receiveMessageRequest = new ReceiveMessageRequest { AttributeNames = { "SentTimestamp" }, MaxNumberOfMessages = 1, MessageAttributeNames = { "All" }, QueueUrl = queueUrl, VisibilityTimeout = 0, WaitTimeSeconds = 0, }; var receiveMessageResponse = await client.ReceiveMessageAsync(receiveMessageRequest); // Delete the received message from the queue. var deleteMessageRequest = new DeleteMessageRequest { QueueUrl = queueUrl, ReceiptHandle = receiveMessageResponse.Messages[0].ReceiptHandle, }; await client.DeleteMessageAsync(deleteMessageRequest); return receiveMessageResponse; } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 DeleteMessage” 中的。

C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Delete a message from an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param messageReceiptHandle: A message receipt handle. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::deleteMessage(const Aws::String &queueUrl, const Aws::String &messageReceiptHandle, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::DeleteMessageRequest request; request.SetQueueUrl(queueUrl); request.SetReceiptHandle(messageReceiptHandle); const Aws::SQS::Model::DeleteMessageOutcome outcome = sqsClient.DeleteMessage( request); if (outcome.IsSuccess()) { std::cout << "Successfully deleted message from queue " << queueUrl << std::endl; } else { std::cerr << "Error deleting message from queue " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • 有关API详细信息,请参阅 “AWS SDK for C++ API参考 DeleteMessage” 中的。

CLI
AWS CLI

删除消息

此示例将删除指定消息。

命令:

aws sqs delete-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --receipt-handle AQEBRXTo...q2doVA==

输出:

None.
Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

try { for (Message message : messages) { DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder() .queueUrl(queueUrl) .receiptHandle(message.receiptHandle()) .build(); sqsClient.deleteMessage(deleteMessageRequest); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); }
  • 有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 DeleteMessage” 中的。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

接收和删除 Amazon SQS 消息。

import { ReceiveMessageCommand, DeleteMessageCommand, SQSClient, DeleteMessageBatchCommand, } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; const receiveMessage = (queueUrl) => client.send( new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], QueueUrl: queueUrl, WaitTimeSeconds: 20, VisibilityTimeout: 20, }), ); export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); if (!Messages) { return; } if (Messages.length === 1) { console.log(Messages[0].Body); await client.send( new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, }), ); } else { await client.send( new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } };
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 DeleteMessage” 中的。

SDK对于 JavaScript (v2)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

接收和删除 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); } }); } });
Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun deleteMessages(queueUrlVal: String) { println("Delete Messages from $queueUrlVal") val purgeRequest = PurgeQueueRequest { queueUrl = queueUrlVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.purgeQueue(purgeRequest) println("Messages are successfully deleted from $queueUrlVal") } } suspend fun deleteQueue(queueUrlVal: String) { val request = DeleteQueueRequest { queueUrl = queueUrlVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.deleteQueue(request) println("$queueUrlVal was deleted!") } }
  • 有关API详细信息,请参阅DeleteMessage中的 Kotlin AWS SDK API 参考

PowerShell
用于 PowerShell

示例 1:此示例从指定队列中删除具有指定收据句柄的消息。

Remove-SQSMessage -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -ReceiptHandle AQEBd329...v6gl8Q==
  • 有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考DeleteMessage中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

def delete_message(message): """ Delete a message from a queue. Clients must delete messages after they are received and processed to remove them from the queue. :param message: The message to delete. The message's queue URL is contained in the message's metadata. :return: None """ try: message.delete() logger.info("Deleted message: %s", message.message_id) except ClientError as error: logger.exception("Couldn't delete message: %s", message.message_id) raise error
  • 有关API详细信息,请参阅DeleteMessage中的 AWS SDKPython (Boto3) API 参考。