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

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

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

DeleteMessageBatch 搭配 AWS SDK或 使用 CLI

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

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Delete a batch of messages from a queue by its url. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteMessageBatchByUrl(string queueUrl, List<Message> messages) { var deleteRequest = new DeleteMessageBatchRequest() { QueueUrl = queueUrl, Entries = new List<DeleteMessageBatchRequestEntry>() }; foreach (var message in messages) { deleteRequest.Entries.Add(new DeleteMessageBatchRequestEntry() { ReceiptHandle = message.ReceiptHandle, Id = message.MessageId }); } var deleteResponse = await _amazonSQSClient.DeleteMessageBatchAsync(deleteRequest); return deleteResponse.Failed.Any(); }
  • 如需API詳細資訊,請參閱 參考 DeleteMessageBatch中的 。 AWS SDK for .NET API

C++
SDK 適用於 C++
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::DeleteMessageBatchRequest request; request.SetQueueUrl(queueURLS[i]); int id = 1; // Ids must be unique within a batch delete request. for (const Aws::String &receiptHandle: receiptHandles) { Aws::SQS::Model::DeleteMessageBatchRequestEntry entry; entry.SetId(std::to_string(id)); ++id; entry.SetReceiptHandle(receiptHandle); request.AddEntries(entry); } Aws::SQS::Model::DeleteMessageBatchOutcome outcome = sqsClient.DeleteMessageBatch(request); if (outcome.IsSuccess()) { std::cout << "The batch deletion of messages was successful." << std::endl; } else { std::cerr << "Error with SQS::DeleteMessageBatch. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; }
  • 如需API詳細資訊,請參閱參考 DeleteMessageBatch中的 AWS SDK for C++ API

CLI
AWS CLI

刪除批次形式的多個訊息

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

命令:

aws sqs delete-message-batch --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --entries file://delete-message-batch.json

輸入檔案 (delete-message-batch.json):

[ { "Id": "FirstMessage", "ReceiptHandle": "AQEB1mgl...Z4GuLw==" }, { "Id": "SecondMessage", "ReceiptHandle": "AQEBLsYM...VQubAA==" } ]

輸出:

{ "Successful": [ { "Id": "FirstMessage" }, { "Id": "SecondMessage" } ] }
Go
SDK for Go V2
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from // an Amazon SQS queue. func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error { entries := make([]types.DeleteMessageBatchRequestEntry, len(messages)) for msgIndex := range messages { entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex)) entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle } _, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{ Entries: entries, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err) } return err }
  • 如需API詳細資訊,請參閱 參考 DeleteMessageBatch中的 。 AWS SDK for Go API

JavaScript
SDK 適用於 JavaScript (v3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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詳細資訊,請參閱 參考 DeleteMessageBatch中的 。 AWS SDK for JavaScript API

PowerShell
適用於 的工具 PowerShell

範例 1:此範例會從指定的佇列刪除具有指定接收控點的 2 則訊息。

$deleteMessageRequest1 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry $deleteMessageRequest1.Id = "Request1" $deleteMessageRequest1.ReceiptHandle = "AQEBX2g4...wtJSQg==" $deleteMessageRequest2 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry $deleteMessageRequest2.Id = "Request2" $deleteMessageRequest2.ReceiptHandle = "AQEBqOVY...KTsLYg==" Remove-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $deleteMessageRequest1, $deleteMessageRequest2

輸出:

Failed Successful ------ ---------- {} {Request1, Request2}
  • 如需API詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考 DeleteMessageBatch中的 。

Python
SDK for Python (Boto3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

def delete_messages(queue, messages): """ Delete a batch of messages from a queue in a single request. :param queue: The queue from which to delete the messages. :param messages: The list of messages to delete. :return: The response from SQS that contains the list of successful and failed message deletions. """ try: entries = [ {"Id": str(ind), "ReceiptHandle": msg.receipt_handle} for ind, msg in enumerate(messages) ] response = queue.delete_messages(Entries=entries) if "Successful" in response: for msg_meta in response["Successful"]: logger.info("Deleted %s", messages[int(msg_meta["Id"])].receipt_handle) if "Failed" in response: for msg_meta in response["Failed"]: logger.warning( "Could not delete %s", messages[int(msg_meta["Id"])].receipt_handle ) except ClientError: logger.exception("Couldn't delete messages from queue %s", queue) else: return response
  • 如需API詳細資訊,請參閱 DeleteMessageBatch 中的 AWS SDK for Python (Boto3) API參考