La versione 4 (V4) di SDK for .NET è disponibile in anteprima! Per visualizzare le informazioni su questa nuova versione in anteprima, consulta la Guida per gli sviluppatori AWS SDK for .NET (anteprima della versione 4).
Tieni presente che la versione 4 dell'SDK è in anteprima, pertanto il suo contenuto è soggetto a modifiche.
Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Questo esempio mostra come utilizzare per inviare messaggi SDK for .NET a una coda Amazon SQS, che puoi creare a livello di codice o utilizzando la console Amazon SQS.
Questo esempio e il prossimo esempio sulla ricezione di messaggi possono essere usati insieme per visualizzare il flusso dei messaggi in Amazon SQS.
Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato il codice completo dell'esempio, che può essere creato ed eseguito così com'è.
Argomenti
Invio di un messaggio
Il seguente frammento invia un messaggio alla coda identificata dall'URL della coda specificato.
L'esempio alla fine di questo argomento mostra questo frammento in 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}");
}
Inviare un batch di messaggi
Il seguente frammento invia un batch di messaggi alla coda identificata dall'URL di coda specificato.
L'esempio alla fine di questo argomento mostra questo frammento in 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.");
}
Eliminare tutti i messaggi dalla coda
Il seguente frammento elimina tutti i messaggi dalla coda identificata dall'URL di coda specificato. Questa operazione è nota anche come eliminazione della coda.
L'esempio alla fine di questo argomento mostra questo frammento in 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}");
}
Codice completo
Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.
NuGet pacchetti:
Elementi di programmazione:
-
Classe Amazon SQSClient
-
Spazio dei nomi Amazon.SQS.Model
Classe PurgeQueueResponse
Classe SendMessageBatchResponse
Classe SendMessageResponse
Classe SendMessageBatchRequestEntry
Classe SendMessageBatchResultEntry
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}");
}
}
}
Ulteriori considerazioni
-
Per informazioni sulle varie limitazioni sui messaggi, inclusi i caratteri consentiti, consulta Quote relative ai messaggi nella Amazon Simple Queue Service Developer Guide.
-
I messaggi rimangono in coda finché non vengono eliminati o la coda non viene eliminata. Quando un messaggio viene ricevuto da un'applicazione, non sarà visibile nella coda anche se esiste ancora nella coda. Per ulteriori informazioni sui timeout di visibilità, consulta Amazon SQS visibility timeout.
-
Oltre al corpo del messaggio, puoi anche aggiungere attributi ai messaggi. Per ulteriori informazioni, consulta Metadati dei messaggi.