Enviando mensagens SMS do Amazon - AWS SDK for .NET

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á.

Enviando mensagens SMS do Amazon

Este exemplo mostra como usar o para enviar mensagens AWS SDK for .NET para uma fila do Amazon SQS, que você pode criar programaticamente ou usando o console do Amazon SQS. A aplicação envia uma única mensagem para a fila e, em seguida, um lote de mensagens. Em seguida, a aplicação aguarda a entrada do usuário, que pode ser mensagens adicionais para enviar para a fila ou uma solicitação para sair da aplicação.

Este exemplo e o próximo exemplo sobre o recebimento de mensagens podem ser usados juntos para ver o fluxo de mensagens no Amazon SQS.

As seções a seguir fornecem snippets desse exemplo. O código completo do exemplo é mostrado depois e pode ser criado e executado como está.

Enviar uma mensagem

O snippet a seguir envia uma mensagem para a fila identificada pelo URL da fila em questão.

O exemplo no final deste tópico mostra o snippet em uso.

// // Method to put a message on a queue // Could be expanded to include message attributes, etc., in a SendMessageRequest private static async Task SendMessage( IAmazonSQS sqsClient, string qUrl, string messageBody) { SendMessageResponse responseSendMsg = await sqsClient.SendMessageAsync(qUrl, messageBody); Console.WriteLine($"Message added to queue\n {qUrl}"); Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}"); }

Enviar um lote de mensagens

O snippet a seguir envia um lote de mensagens para a fila identificada pelo URL da fila em questão.

O exemplo no final deste tópico mostra o snippet em uso.

// // Method to put a batch of messages on a queue // Could be expanded to include message attributes, etc., // in the SendMessageBatchRequestEntry objects private static async Task SendMessageBatch( IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages) { Console.WriteLine($"\nSending a batch of messages to queue\n {qUrl}"); SendMessageBatchResponse responseSendBatch = await sqsClient.SendMessageBatchAsync(qUrl, messages); // Could test responseSendBatch.Failed here foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful) Console.WriteLine($"Message {entry.Id} successfully queued."); }

Excluir todas as mensagens da fila

O snippet a seguir exclui todas as mensagens da fila identificada pelo URL da fila em questão. Isso também é conhecido como limpando a fila.

O exemplo no final deste tópico mostra o snippet em uso.

// // Method to delete all messages from the queue private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl) { Console.WriteLine($"\nPurging messages from queue\n {qUrl}..."); PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl); Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}"); }

Código completo

Esta seção mostra as referências relevantes e o código completo desse exemplo.

NuGet pacotes:

Elementos de programação:

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SQS; using Amazon.SQS.Model; namespace SQSSendMessages { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to send messages to a queue class Program { // Some example messages to send to the queue private const string JsonMessage = "{\"product\":[{\"name\":\"Product A\",\"price\": \"32\"},{\"name\": \"Product B\",\"price\": \"27\"}]}"; private const string XmlMessage = "<products><product name=\"Product A\" price=\"32\" /><product name=\"Product B\" price=\"27\" /></products>"; private const string CustomMessage = "||product|Product A|32||product|Product B|27||"; private const string TextMessage = "Just a plain text message."; static async Task Main(string[] args) { // Do some checks on the command-line if(args.Length == 0) { Console.WriteLine("\nUsage: SQSSendMessages queue_url"); Console.WriteLine(" queue_url - The URL of an existing SQS queue."); return; } if(!args[0].StartsWith("https://sqs.")) { Console.WriteLine("\nThe command-line argument isn't a queue URL:"); Console.WriteLine($"{args[0]}"); return; } // Create the Amazon SQS client var sqsClient = new AmazonSQSClient(); // (could verify that the queue exists) // Send some example messages to the given queue // A single message await SendMessage(sqsClient, args[0], JsonMessage); // A batch of messages var batchMessages = new List<SendMessageBatchRequestEntry>{ new SendMessageBatchRequestEntry("xmlMsg", XmlMessage), new SendMessageBatchRequestEntry("customeMsg", CustomMessage), new SendMessageBatchRequestEntry("textMsg", TextMessage)}; await SendMessageBatch(sqsClient, args[0], batchMessages); // Let the user send their own messages or quit await InteractWithUser(sqsClient, args[0]); // Delete all messages that are still in the queue await DeleteAllMessages(sqsClient, args[0]); } // // Method to put a message on a queue // Could be expanded to include message attributes, etc., in a SendMessageRequest private static async Task SendMessage( IAmazonSQS sqsClient, string qUrl, string messageBody) { SendMessageResponse responseSendMsg = await sqsClient.SendMessageAsync(qUrl, messageBody); Console.WriteLine($"Message added to queue\n {qUrl}"); Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}"); } // // Method to put a batch of messages on a queue // Could be expanded to include message attributes, etc., // in the SendMessageBatchRequestEntry objects private static async Task SendMessageBatch( IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages) { Console.WriteLine($"\nSending a batch of messages to queue\n {qUrl}"); SendMessageBatchResponse responseSendBatch = await sqsClient.SendMessageBatchAsync(qUrl, messages); // Could test responseSendBatch.Failed here foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful) Console.WriteLine($"Message {entry.Id} successfully queued."); } // // Method to get input from the user // They can provide messages to put in the queue or exit the application private static async Task InteractWithUser(IAmazonSQS sqsClient, string qUrl) { string response; while (true) { // Get the user's input Console.WriteLine("\nType a message for the queue or \"exit\" to quit:"); response = Console.ReadLine(); if(response.ToLower() == "exit") break; // Put the user's message in the queue await SendMessage(sqsClient, qUrl, response); } } // // Method to delete all messages from the queue private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl) { Console.WriteLine($"\nPurging messages from queue\n {qUrl}..."); PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl); Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}"); } } }

Considerações adicionais

  • As mensagens permanecem nas filas até serem excluídas ou a fila ser removida. Quando uma mensagem for recebida por uma aplicação, ela não ficará visível na fila, mesmo que ainda exista na fila. Para obter mais informações sobre tempos limite de visibilidade, consulte Tempo limite de visibilidade do Amazon SQS.

  • Além do corpo da mensagem, você também pode adicionar atributos às mensagens. Para obter mais informações, consulte Mensagem de metadados.