DeleteMessage 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

DeleteMessage 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 DeleteMessage

.NET
AWS SDK for .NET
注意

還有更多 on 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 詳細資訊,請參閱 DeleteMessage AWS SDK for .NET 參考中的 API

C++
C++ 的 SDK
注意

還有更多 on 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 詳細資訊,請參閱 DeleteMessage AWS SDK for C++ 參考中的 API

CLI
AWS CLI

刪除訊息

此範例會刪除指定的訊息。

命令:

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

輸出:

None.
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 DeleteMessage

Java
Java 2.x 的 SDK
注意

還有更多 on 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 詳細資訊,請參閱 DeleteMessage AWS SDK for Java 2.x 參考中的 API

JavaScript
SDK for JavaScript (v3)
注意

還有更多 on 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 詳細資訊,請參閱 DeleteMessage AWS SDK for JavaScript 參考中的 API

SDK for JavaScript (v2)
注意

還有更多 on 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
Kotlin 的 SDK
注意

還有更多 on 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 AWS for Kotlin SDK 參考中的 API

PowerShell
for 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
Python 的 SDK (Boto3)
注意

還有更多 on 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 SDK for Python (Boto3) Word 參考中的 API