AWS SDK を使用して Amazon SQS キューにメッセージのバッチを送信する - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK を使用して Amazon SQS キューにメッセージのバッチを送信する

次のコード例は、Amazon SQS キューにバッチメッセージを送信する方法を示しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。

CLI
AWS CLI

複数のメッセージを一括送信するには

この例は、メッセージ本文、遅延期間、およびメッセージ属性を指定した 2 つのメッセージを指定されたキューに送信します。

コマンド:

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

入力ファイル (send-message-batch.json):

[ { "Id": "FuelReport-0001-2015-09-16T140731Z", "MessageBody": "Fuel report for account 0001 on 2015-09-16 at 02:07:31 PM.", "DelaySeconds": 10, "MessageAttributes": { "SellerName": { "DataType": "String", "StringValue": "Example Store" }, "City": { "DataType": "String", "StringValue": "Any City" }, "Region": { "DataType": "String", "StringValue": "WA" }, "PostalCode": { "DataType": "String", "StringValue": "99065" }, "PricePerGallon": { "DataType": "Number", "StringValue": "1.99" } } }, { "Id": "FuelReport-0002-2015-09-16T140930Z", "MessageBody": "Fuel report for account 0002 on 2015-09-16 at 02:09:30 PM.", "DelaySeconds": 10, "MessageAttributes": { "SellerName": { "DataType": "String", "StringValue": "Example Fuels" }, "City": { "DataType": "String", "StringValue": "North Town" }, "Region": { "DataType": "String", "StringValue": "WA" }, "PostalCode": { "DataType": "String", "StringValue": "99123" }, "PricePerGallon": { "DataType": "Number", "StringValue": "1.87" } } } ]

出力:

{ "Successful": [ { "MD5OfMessageBody": "203c4a38...7943237e", "MD5OfMessageAttributes": "10809b55...baf283ef", "Id": "FuelReport-0001-2015-09-16T140731Z", "MessageId": "d175070c-d6b8-4101-861d-adeb3EXAMPLE" }, { "MD5OfMessageBody": "2cf0159a...c1980595", "MD5OfMessageAttributes": "55623928...ae354a25", "Id": "FuelReport-0002-2015-09-16T140930Z", "MessageId": "f9b7d55d-0570-413e-b9c5-a9264EXAMPLE" } ] }
  • API の詳細については、「 コマンドリファレンスSendMessageBatch」の「」を参照してください。 AWS CLI

Java
SDK for Java 2.x
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(), SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10) .build()) .build(); sqsClient.sendMessageBatch(sendMessageBatchRequest);
  • API の詳細については、「 API リファレンスSendMessageBatch」の「」を参照してください。 AWS SDK for Java 2.x

Python
SDK for Python (Boto3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

def send_messages(queue, messages): """ Send a batch of messages in a single request to an SQS queue. This request may return overall success even when some messages were not sent. The caller must inspect the Successful and Failed lists in the response and resend any failed messages. :param queue: The queue to receive the messages. :param messages: The messages to send to the queue. These are simplified to contain only the message body and attributes. :return: The response from SQS that contains the list of successful and failed messages. """ try: entries = [ { "Id": str(ind), "MessageBody": msg["body"], "MessageAttributes": msg["attributes"], } for ind, msg in enumerate(messages) ] response = queue.send_messages(Entries=entries) if "Successful" in response: for msg_meta in response["Successful"]: logger.info( "Message sent: %s: %s", msg_meta["MessageId"], messages[int(msg_meta["Id"])]["body"], ) if "Failed" in response: for msg_meta in response["Failed"]: logger.warning( "Failed to send: %s: %s", msg_meta["MessageId"], messages[int(msg_meta["Id"])]["body"], ) except ClientError as error: logger.exception("Send messages failed to queue: %s", queue) raise error else: return response
  • API の詳細については、SendMessageBatchAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

Ruby
SDK for Ruby
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

require "aws-sdk-sqs" require "aws-sdk-sts" # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param entries [Hash] The contents of the messages to be sent, # in the correct format. # @return [Boolean] true if the messages were sent; otherwise, false. # @example # exit 1 unless messages_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # [ # { # id: 'Message1', # message_body: 'This is the first message.' # }, # { # id: 'Message2', # message_body: 'This is the second message.' # } # ] # ) def messages_sent?(sqs_client, queue_url, entries) sqs_client.send_message_batch( queue_url: queue_url, entries: entries ) true rescue StandardError => e puts "Error sending messages: #{e.message}" false end # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me region = "us-west-2" queue_name = "my-queue" entries = [ { id: "Message1", message_body: "This is the first message." }, { id: "Message2", message_body: "This is the second message." } ] sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' queue_url = "https://sqs." + region + ".amazonaws.com/" + sts_client.get_caller_identity.account + "/" + queue_name sqs_client = Aws::SQS::Client.new(region: region) puts "Sending messages to the queue named '#{queue_name}'..." if messages_sent?(sqs_client, queue_url, entries) puts "Messages sent." else puts "Messages not sent." end end
  • API の詳細については、「 API リファレンスSendMessageBatch」の「」を参照してください。 AWS SDK for Ruby