Use SendMessage com um AWS SDK ou CLI - AWS SDK Exemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use SendMessage com um AWS SDK ou CLI

Os exemplos de códigos a seguir mostram como usar SendMessage.

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Crie uma SQS fila da Amazon e envie uma mensagem para ela.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon; using Amazon.SQS; using Amazon.SQS.Model; public class CreateSendExample { // Specify your AWS Region (an example Region is shown). private static readonly string QueueName = "Example_Queue"; private static readonly RegionEndpoint ServiceRegion = RegionEndpoint.USWest2; private static IAmazonSQS client; public static async Task Main() { client = new AmazonSQSClient(ServiceRegion); var createQueueResponse = await CreateQueue(client, QueueName); string queueUrl = createQueueResponse.QueueUrl; Dictionary<string, MessageAttributeValue> messageAttributes = new Dictionary<string, MessageAttributeValue> { { "Title", new MessageAttributeValue { DataType = "String", StringValue = "The Whistler" } }, { "Author", new MessageAttributeValue { DataType = "String", StringValue = "John Grisham" } }, { "WeeksOn", new MessageAttributeValue { DataType = "Number", StringValue = "6" } }, }; string messageBody = "Information about current NY Times fiction bestseller for week of 12/11/2016."; var sendMsgResponse = await SendMessage(client, queueUrl, messageBody, messageAttributes); } /// <summary> /// Creates a new Amazon SQS queue using the queue name passed to it /// in queueName. /// </summary> /// <param name="client">An SQS client object used to send the message.</param> /// <param name="queueName">A string representing the name of the queue /// to create.</param> /// <returns>A CreateQueueResponse that contains information about the /// newly created queue.</returns> public static async Task<CreateQueueResponse> CreateQueue(IAmazonSQS client, string queueName) { var request = new CreateQueueRequest { QueueName = queueName, Attributes = new Dictionary<string, string> { { "DelaySeconds", "60" }, { "MessageRetentionPeriod", "86400" }, }, }; var response = await client.CreateQueueAsync(request); Console.WriteLine($"Created a queue with URL : {response.QueueUrl}"); return response; } /// <summary> /// Sends a message to an SQS queue. /// </summary> /// <param name="client">An SQS client object used to send the message.</param> /// <param name="queueUrl">The URL of the queue to which to send the /// message.</param> /// <param name="messageBody">A string representing the body of the /// message to be sent to the queue.</param> /// <param name="messageAttributes">Attributes for the message to be /// sent to the queue.</param> /// <returns>A SendMessageResponse object that contains information /// about the message that was sent.</returns> public static async Task<SendMessageResponse> SendMessage( IAmazonSQS client, string queueUrl, string messageBody, Dictionary<string, MessageAttributeValue> messageAttributes) { var sendMessageRequest = new SendMessageRequest { DelaySeconds = 10, MessageAttributes = messageAttributes, MessageBody = messageBody, QueueUrl = queueUrl, }; var response = await client.SendMessageAsync(sendMessageRequest); Console.WriteLine($"Sent a message with id : {response.MessageId}"); return response; } }
  • Para API obter detalhes, consulte SendMessageem AWS SDK for .NET APIReferência.

C++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Send a message to an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param messageBody: A message body. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::sendMessage(const Aws::String &queueUrl, const Aws::String &messageBody, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SendMessageRequest request; request.SetQueueUrl(queueUrl); request.SetMessageBody(messageBody); const Aws::SQS::Model::SendMessageOutcome outcome = sqsClient.SendMessage(request); if (outcome.IsSuccess()) { std::cout << "Successfully sent message to " << queueUrl << std::endl; } else { std::cerr << "Error sending message to " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • Para API obter detalhes, consulte SendMessageem AWS SDK for C++ APIReferência.

CLI
AWS CLI

Para enviar uma mensagem

Este exemplo envia uma mensagem com o corpo da mensagem, o período de atraso e os atributos da mensagem especificados para a fila especificada.

Comando:

aws sqs send-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --message-body "Information about the largest city in Any Region." --delay-seconds 10 --message-attributes file://send-message.json

Arquivo de entrada (send-message.json):

{ "City": { "DataType": "String", "StringValue": "Any City" }, "Greeting": { "DataType": "Binary", "BinaryValue": "Hello, World!" }, "Population": { "DataType": "Number", "StringValue": "1250800" } }

Saída:

{ "MD5OfMessageBody": "51b0a325...39163aa0", "MD5OfMessageAttributes": "00484c68...59e48f06", "MessageId": "da68f62c-0c07-4bee-bf5f-7e856EXAMPLE" }
  • Para API obter detalhes, consulte SendMessagena Referência de AWS CLI Comandos.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SqsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SendMessages { public static void main(String[] args) { final String usage = """ Usage: <queueName> <message> Where: queueName - The name of the queue. message - The message to send. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String queueName = args[0]; String message = args[1]; SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); sendMessage(sqsClient, queueName, message); sqsClient.close(); } public static void sendMessage(SqsClient sqsClient, String queueName, String message) { try { CreateQueueRequest request = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(request); GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl(); SendMessageRequest sendMsgRequest = SendMessageRequest.builder() .queueUrl(queueUrl) .messageBody(message) .delaySeconds(5) .build(); sqsClient.sendMessage(sendMsgRequest); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para API obter detalhes, consulte SendMessageem AWS SDK for Java 2.x APIReferência.

JavaScript
SDKpara JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Envie uma mensagem para uma SQS fila da Amazon.

import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; export const main = async (sqsQueueUrl = SQS_QUEUE_URL) => { const command = new SendMessageCommand({ QueueUrl: sqsQueueUrl, DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", }); const response = await client.send(command); console.log(response); return response; };
SDKpara JavaScript (v2)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Envie uma mensagem para uma SQS fila da Amazon.

// 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 params = { // Remove DelaySeconds parameter and value for FIFO queues DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", // MessageDeduplicationId: "TheWhistler", // Required for FIFO queues // MessageGroupId: "Group1", // Required for FIFO queues QueueUrl: "SQS_QUEUE_URL", }; sqs.sendMessage(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.MessageId); } });
Kotlin
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

suspend fun sendMessages( queueUrlVal: String, message: String, ) { println("Sending multiple messages") println("\nSend message") val sendRequest = SendMessageRequest { queueUrl = queueUrlVal messageBody = message delaySeconds = 10 } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.sendMessage(sendRequest) println("A single message was successfully sent.") } } suspend fun sendBatchMessages(queueUrlVal: String?) { println("Sending multiple messages") val msg1 = SendMessageBatchRequestEntry { id = "id1" messageBody = "Hello from msg 1" } val msg2 = SendMessageBatchRequestEntry { id = "id2" messageBody = "Hello from msg 2" } val sendMessageBatchRequest = SendMessageBatchRequest { queueUrl = queueUrlVal entries = listOf(msg1, msg2) } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.sendMessageBatch(sendMessageBatchRequest) println("Batch message were successfully sent.") } }
  • Para API obter detalhes, consulte a SendMessagereferência AWS SDKdo Kotlin API.

PowerShell
Ferramentas para PowerShell

Exemplo 1: Este exemplo envia uma mensagem com os atributos e o corpo da mensagem especificados para a fila especificada, com a entrega da mensagem atrasada por 10 segundos.

$cityAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $cityAttributeValue.DataType = "String" $cityAttributeValue.StringValue = "AnyCity" $populationAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $populationAttributeValue.DataType = "Number" $populationAttributeValue.StringValue = "1250800" $messageAttributes = New-Object System.Collections.Hashtable $messageAttributes.Add("City", $cityAttributeValue) $messageAttributes.Add("Population", $populationAttributeValue) Send-SQSMessage -DelayInSeconds 10 -MessageAttributes $messageAttributes -MessageBody "Information about the largest city in Any Region." -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue

Saída:

MD5OfMessageAttributes MD5OfMessageBody MessageId ---------------------- ---------------- --------- 1d3e51347bc042efbdf6dda31EXAMPLE 51b0a3256d59467f973009b73EXAMPLE c35fed8f-c739-4d0c-818b-1820eEXAMPLE
  • Para API obter detalhes, consulte SendMessageem Referência de AWS Tools for PowerShell cmdlet.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

def send_message(queue, message_body, message_attributes=None): """ Send a message to an Amazon SQS queue. :param queue: The queue that receives the message. :param message_body: The body text of the message. :param message_attributes: Custom attributes of the message. These are key-value pairs that can be whatever you want. :return: The response from SQS that contains the assigned message ID. """ if not message_attributes: message_attributes = {} try: response = queue.send_message( MessageBody=message_body, MessageAttributes=message_attributes ) except ClientError as error: logger.exception("Send message failed: %s", message_body) raise error else: return response
  • Para API obter detalhes, consulte a SendMessageReferência AWS SDK do Python (Boto3). API

Ruby
SDKpara Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

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 message_body [String] The contents of the message to be sent. # @return [Boolean] true if the message was sent; otherwise, false. # @example # exit 1 unless message_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # 'This is my message.' # ) def message_sent?(sqs_client, queue_url, message_body) sqs_client.send_message( queue_url: queue_url, message_body: message_body ) true rescue StandardError => e puts "Error sending message: #{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" message_body = "This is my 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 a message to the queue named '#{queue_name}'..." if message_sent?(sqs_client, queue_url, message_body) puts "Message sent." else puts "Message not sent." end end # Example usage: run_me if $PROGRAM_NAME == __FILE__
  • Para API obter detalhes, consulte SendMessageem AWS SDK for Ruby APIReferência.

Rust
SDKpara Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

async fn send(client: &Client, queue_url: &String, message: &SQSMessage) -> Result<(), Error> { println!("Sending message to queue with URL: {}", queue_url); let rsp = client .send_message() .queue_url(queue_url) .message_body(&message.body) // If the queue is FIFO, you need to set .message_deduplication_id // and message_group_id or configure the queue for ContentBasedDeduplication. .send() .await?; println!("Send message to the queue: {:#?}", rsp); Ok(()) }
  • Para API obter detalhes, consulte SendMessagea AWS SDKAPIreferência do Rust.

SAP ABAP
SDKpara SAP ABAP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

TRY. oo_result = lo_sqs->sendmessage( " oo_result is returned for testing purposes. " iv_queueurl = iv_queue_url iv_messagebody = iv_message ). MESSAGE 'Message sent to SQS queue.' TYPE 'I'. CATCH /aws1/cx_sqsinvalidmsgconts. MESSAGE 'Message contains non-valid characters.' TYPE 'E'. CATCH /aws1/cx_sqsunsupportedop. MESSAGE 'Operation not supported.' TYPE 'E'. ENDTRY.
  • Para API obter detalhes, consulte SendMessage AWSSDKpara SAP ABAP API referência.