Envío de SQS mensajes a Amazon - AWS SDK for .NET

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.

Envío de SQS mensajes a Amazon

En este ejemplo, se muestra cómo utilizarla AWS SDK for .NET para enviar mensajes a una SQS cola de Amazon, que puede crear mediante programación o mediante la consola de Amazon. SQS La aplicación envía un único mensaje a la cola y, a continuación, un lote de mensajes. Después, la aplicación espera a que el usuario especifique información, que pueden ser más mensajes para enviarlos a la cola o una solicitud para salir de la aplicación.

Este ejemplo y el siguiente sobre la recepción de mensajes se pueden usar juntos para ver el flujo de mensajes en AmazonSQS.

En las siguientes secciones se proporcionan fragmentos de código de este ejemplo. Tras ello, se muestra el código completo del ejemplo, que se puede compilar y ejecutar tal cual.

Enviar un mensaje

El siguiente fragmento envía un mensaje a la cola identificada por la cola en cuestión. URL

El ejemplo que aparece al final de este tema muestra este fragmento de código en 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}"); }

Envío de un lote de mensajes

El siguiente fragmento envía un lote de mensajes a la cola identificada por la cola en cuestión. URL

El ejemplo que aparece al final de este tema muestra este fragmento de código en 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."); }

Eliminación de todos los mensajes de la cola

El siguiente fragmento elimina todos los mensajes de la cola identificada por la cola en cuestión. URL Esto se conoce también como purgar la cola.

El ejemplo que aparece al final de este tema muestra este fragmento de código en 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

En esta sección se muestran las referencias relevantes y el código completo de este ejemplo.

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}"); } } }

Consideraciones adicionales

  • Los mensajes permanecen en las colas hasta que se eliminan o hasta que la cola se purga. Cuando una aplicación ha recibido un mensaje, este no estará visible en la cola aunque siga existiendo en ella. Para obtener más información sobre los tiempos de espera de visibilidad, consulta los tiempos de espera de SQS visibilidad de Amazon.

  • Además del cuerpo del mensaje, también se pueden agregar atributos a los mensajes. Para obtener más información, consulte Metadatos de mensajes.