Úselo SendMessageBatch con un AWS SDK o CLI - AWS Ejemplos de código de SDK

Hay más ejemplos de AWS SDK disponibles en el GitHub repositorio de ejemplos de AWS Doc SDK.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Úselo SendMessageBatch con un AWS SDK o CLI

En los siguientes ejemplos de código, se muestra cómo utilizar SendMessageBatch.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

CLI
AWS CLI

Envío de varios mensajes por lotes

En este ejemplo, se envían 2 mensajes con los cuerpos de los mensajes, los períodos de retraso y los atributos de los mensajes especificados a la cola especificada.

Comando:

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

Archivo de entrada (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" } } } ]

Salida:

{ "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" } ] }
  • Para obtener más información sobre la API, consulte SendMessageBatchla Referencia de AWS CLI comandos.

Java
SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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);
  • Para obtener más información sobre la API, consulta SendMessageBatchla Referencia AWS SDK for Java 2.x de la API.

PowerShell
Herramientas para PowerShell

Ejemplo 1: Este ejemplo envía 2 mensajes con los atributos y cuerpos de mensaje especificados a la cola especificada. La entrega se retrasa 15 segundos para el primer mensaje y 10 segundos para el segundo mensaje.

$student1NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student1NameAttributeValue.DataType = "String" $student1NameAttributeValue.StringValue = "John Doe" $student1GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student1GradeAttributeValue.DataType = "Number" $student1GradeAttributeValue.StringValue = "89" $student2NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student2NameAttributeValue.DataType = "String" $student2NameAttributeValue.StringValue = "Jane Doe" $student2GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student2GradeAttributeValue.DataType = "Number" $student2GradeAttributeValue.StringValue = "93" $message1 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry $message1.DelaySeconds = 15 $message1.Id = "FirstMessage" $message1.MessageAttributes.Add("StudentName", $student1NameAttributeValue) $message1.MessageAttributes.Add("StudentGrade", $student1GradeAttributeValue) $message1.MessageBody = "Information about John Doe's grade." $message2 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry $message2.DelaySeconds = 10 $message2.Id = "SecondMessage" $message2.MessageAttributes.Add("StudentName", $student2NameAttributeValue) $message2.MessageAttributes.Add("StudentGrade", $student2GradeAttributeValue) $message2.MessageBody = "Information about Jane Doe's grade." Send-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $message1, $message2

Salida:

Failed Successful ------ ---------- {} {FirstMessage, SecondMessage}
  • Para obtener más información sobre la API, consulte SendMessageBatchla Referencia de AWS Tools for PowerShell cmdlets.

Python
SDK para Python (Boto3)
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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
  • Para obtener más información sobre la API, consulta SendMessageBatchla AWS Referencia de API de SDK for Python (Boto3).

Ruby
SDK para Ruby
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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
  • Para obtener más información sobre la API, consulta SendMessageBatchla Referencia AWS SDK for Ruby de la API.