Pubblica messaggi con il AWS Message Processing Framework per .NET - AWS SDK for .NET

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

Pubblica messaggi con il AWS Message Processing Framework per .NET

Questa è la documentazione preliminare per una funzionalità della versione di anteprima. ed è soggetta a modifiche.

Il AWS Message Processing Framework for .NET supporta la pubblicazione di uno o più tipi di messaggi, l'elaborazione di uno o più tipi di messaggi o l'esecuzione di entrambe le operazioni nella stessa applicazione.

Il codice seguente mostra una configurazione per un'applicazione che pubblica tipi di messaggi diversi su AWS servizi diversi.

var builder = WebApplication.CreateBuilder(args); // Register the AWS Message Processing Framework for .NET builder.Services.AddAWSMessageBus(builder => { // Register that you'll send messages of type ChatMessage to an existing queue builder.AddSQSPublisher<ChatMessage>("https://sqs.us-west-2.amazonaws.com/012345678910/MyAppProd"); // Register that you'll publish messages of type OrderInfo to an existing SNS topic builder.AddSNSPublisher<OrderInfo>("arn:aws:sns:us-west-2:012345678910:MyAppProd"); // Register that you'll publish messages of type FoodItem to an existing EventBridge bus builder.AddEventBridgePublisher<FoodItem>("arn:aws:events:us-west-2:012345678910:event-bus/default"); });

Dopo aver registrato il framework durante l'avvio, inserisci il generico IMessagePublisher nel tuo codice. Chiama il suo PublishAsync metodo per pubblicare uno qualsiasi dei tipi di messaggio configurati sopra. L'editore generico determinerà la destinazione verso cui indirizzare il messaggio in base al tipo.

Nell'esempio seguente, un controller ASP.NET MVC riceve sia ChatMessage messaggi che OrderInfo eventi dagli utenti, quindi li pubblica rispettivamente su Amazon SQS e Amazon SNS. Entrambi i tipi di messaggi possono essere pubblicati utilizzando l'editore generico configurato in precedenza.

[ApiController] [Route("[controller]")] public class PublisherController : ControllerBase { private readonly IMessagePublisher _messagePublisher; public PublisherController(IMessagePublisher messagePublisher) { _messagePublisher = messagePublisher; } [HttpPost("chatmessage", Name = "Chat Message")] public async Task<IActionResult> PublishChatMessage([FromBody] ChatMessage message) { // Perform business and validation logic on the ChatMessage here. if (message == null) { return BadRequest("A chat message was not submitted. Unable to forward to the message queue."); } if (string.IsNullOrEmpty(message.MessageDescription)) { return BadRequest("The MessageDescription cannot be null or empty."); } // Send the ChatMessage to SQS, using the generic publisher. await _messagePublisher.PublishAsync(message); return Ok(); } [HttpPost("order", Name = "Order")] public async Task<IActionResult> PublishOrder([FromBody] OrderInfo message) { if (message == null) { return BadRequest("An order was not submitted."); } // Publish the OrderInfo to SNS, using the generic publisher. await _messagePublisher.PublishAsync(message); return Ok(); } }

Per indirizzare un messaggio alla logica di gestione appropriata, il framework utilizza dei metadati denominati identificatori del tipo di messaggio. Per impostazione predefinita, si tratta del nome completo del tipo.NET del messaggio, incluso il nome dell'assembly. Se state inviando e gestendo messaggi, questo meccanismo funziona bene se condividete la definizione degli oggetti del messaggio tra progetti. Tuttavia, se i messaggi vengono ridefiniti in diversi namespace o se state scambiando messaggi con altri framework o linguaggi di programmazione, potrebbe essere necessario sostituire l'identificatore del tipo di messaggio.

var builder = Host.CreateDefaultBuilder(args); builder.ConfigureServices(services => { // Register the AWS Message Processing Framework for .NET services.AddAWSMessageBus(builder => { // Register that you'll publish messages of type GreetingMessage to an existing queue builder.AddSQSPublisher<GreetingMessage>("https://sqs.us-west-2.amazonaws.com/012345678910/MyAppProd", "greetingMessage"); }); });

Editori specifici per servizi

L'esempio mostrato sopra utilizza il formato genericoIMessagePublisher, che può essere pubblicato su qualsiasi AWS servizio supportato in base al tipo di messaggio configurato. Il framework fornisce anche editori specifici per servizi per Amazon SQS, Amazon SNS e Amazon. EventBridge Questi editori specifici espongono opzioni che si applicano solo a quel servizio e che possono essere inserite utilizzando i tipi, e. ISQSPublisher ISNSPublisher IEventBridgePublisher

Ad esempio, quando si inviano messaggi a una coda FIFO SQS, è necessario impostare l'ID del gruppo di messaggi appropriato. Il codice seguente mostra nuovamente l'ChatMessageesempio, ma ora viene utilizzato un ISQSPublisher per impostare opzioni specifiche di SQS.

public class PublisherController : ControllerBase { private readonly ISQSPublisher _sqsPublisher; public PublisherController(ISQSPublisher sqsPublisher) { _sqsPublisher = sqsPublisher; } [HttpPost("chatmessage", Name = "Chat Message")] public async Task<IActionResult> PublishChatMessage([FromBody] ChatMessage message) { // Perform business and validation logic on the ChatMessage here if (message == null) { return BadRequest("A chat message was not submitted. Unable to forward to the message queue."); } if (string.IsNullOrEmpty(message.MessageDescription)) { return BadRequest("The MessageDescription cannot be null or empty."); } // Send the ChatMessage to SQS using the injected ISQSPublisher, with SQS-specific options await _sqsPublisher.SendAsync(message, new SQSOptions { DelaySeconds = <delay-in-seconds>, MessageAttributes = <message-attributes>, MessageDeduplicationId = <message-deduplication-id>, MessageGroupId = <message-group-id> }); return Ok(); } }

Lo stesso può essere fatto per SNS e EventBridge, rispettivamente, utilizzando ISNSPublisher e. IEventBridgePublisher

await _snsPublisher.PublishAsync(message, new SNSOptions { Subject = <subject>, MessageAttributes = <message-attributes>, MessageDeduplicationId = <message-deduplication-id>, MessageGroupId = <message-group-id> });
await _eventBridgePublisher.PublishAsync(message, new EventBridgeOptions { DetailType = <detail-type>, Resources = <resources>, Source = <source>, Time = <time>, TraceHeader = <trace-header> });

Per impostazione predefinita, i messaggi di un determinato tipo vengono inviati alla destinazione configurata in anticipo. Tuttavia, puoi sovrascrivere la destinazione di un singolo messaggio utilizzando gli editori specifici del messaggio. Puoi anche sostituire il AWS SDK for .NET client sottostante utilizzato per pubblicare il messaggio, il che può essere utile nelle applicazioni multi-tenant in cui è necessario modificare ruoli o credenziali, a seconda della destinazione.

await _sqsPublisher.SendAsync(message, new SQSOptions { OverrideClient = <override IAmazonSQS client>, QueueUrl = <override queue URL> });