Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen
Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Gunakan DeleteMessageBatch
dengan AWS SDK atau CLI
Contoh kode berikut menunjukkan cara menggunakanDeleteMessageBatch
.
Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:
- .NET
-
- AWS SDK for .NET
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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(); }
-
Untuk API detailnya, lihat DeleteMessageBatchdi AWS SDK for .NET APIReferensi.
-
- C++
-
- SDKuntuk C ++
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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; }
-
Untuk API detailnya, lihat DeleteMessageBatchdi AWS SDK for C++ APIReferensi.
-
- CLI
-
- AWS CLI
-
Untuk menghapus beberapa pesan sebagai batch
Contoh ini menghapus pesan yang ditentukan.
Perintah:
aws sqs delete-message-batch --queue-url
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
--entriesfile://delete-message-batch.json
Berkas masukan (delete-message-batch.json):
[ { "Id": "FirstMessage", "ReceiptHandle": "AQEB1mgl...Z4GuLw==" }, { "Id": "SecondMessage", "ReceiptHandle": "AQEBLsYM...VQubAA==" } ]
Output:
{ "Successful": [ { "Id": "FirstMessage" }, { "Id": "SecondMessage" } ] }
-
Untuk API detailnya, lihat DeleteMessageBatch
di Referensi AWS CLI Perintah.
-
- Go
-
- SDKuntuk Go V2
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 }
-
Untuk API detailnya, lihat DeleteMessageBatch
di AWS SDK for Go APIReferensi.
-
- JavaScript
-
- SDKuntuk JavaScript (v3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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, })), }), ); } };
-
Untuk API detailnya, lihat DeleteMessageBatchdi AWS SDK for JavaScript APIReferensi.
-
- PowerShell
-
- Alat untuk PowerShell
-
Contoh 1: Contoh ini menghapus 2 pesan dengan pegangan tanda terima yang ditentukan dari antrian yang ditentukan.
$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
Output:
Failed Successful ------ ---------- {} {Request1, Request2}
-
Untuk API detailnya, lihat DeleteMessageBatchdi AWS Tools for PowerShell Referensi Cmdlet.
-
- Python
-
- SDKuntuk Python (Boto3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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
-
Untuk API detailnya, lihat DeleteMessageBatch AWSSDKReferensi Python (Boto3). API
-