

第 4 版 (V4) 適用於 .NET 的 AWS SDK 已發行！

如需有關中斷變更和遷移應用程式的資訊，請參閱[遷移主題](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用適用於 .NET 的訊息處理架構發佈 AWS 訊息
<a name="msg-proc-fw-publish"></a>

.NET AWS 的訊息處理架構支援發佈一或多個訊息類型、處理一或多個訊息類型，或在相同的應用程式中同時執行兩者。

下列程式碼顯示將不同訊息類型發佈至不同 AWS 服務之應用程式的組態。

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

在啟動期間註冊架構後，請將一般 插入`IMessagePublisher`您的程式碼。呼叫其 `PublishAsync` 方法來發佈上述設定的任何訊息類型。一般發佈者會根據訊息的類型，決定要將訊息路由到 的目的地。

 在下列範例中，ASP.NET MVC 控制器會收到來自使用者`ChatMessage`的訊息和`OrderInfo`事件，然後將其分別發佈到 Amazon SQS 和 Amazon SNS。這兩種訊息類型都可以使用上面設定的一般發佈者來發佈。

```
[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();
    }
}
```

為了將訊息路由到適當的處理邏輯，架構會使用稱為*訊息類型識別符*的中繼資料。根據預設，這是訊息 .NET 類型的全名，包括其組件名稱。如果您同時傳送和處理訊息，如果您跨專案共用訊息物件的定義，則此機制會正常運作。不過，如果訊息是在不同的命名空間中重新定義，或者如果您要與其他架構或程式設計語言交換訊息，則您可能需要覆寫訊息類型識別符。

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

## 服務特定的發佈者
<a name="service-specific-publishers"></a>

上述範例使用一般 `IMessagePublisher`，可根據設定的訊息類型發佈到任何支援的 AWS 服務。此架構也為 Amazon SQS、Amazon SNS 和 Amazon EventBridge 提供服務特定的發佈者。這些特定發佈者公開僅適用於該服務的選項，並且可以使用類型 `ISQSPublisher`、 `ISNSPublisher`和 注入`IEventBridgePublisher`。

例如，傳送訊息至 SQS FIFO 佇列時，您必須設定適當的[訊息群組 ID](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-key-terms.html)。下列程式碼再次顯示`ChatMessage`範例，但現在使用 `ISQSPublisher`來設定 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();
    }
}
```

您可以`IEventBridgePublisher`分別使用 和 對 SNS `ISNSPublisher`和 EventBridge 進行相同的操作。

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

根據預設，指定類型的訊息會傳送至預先設定的目的地。不過，您可以使用訊息特定的發佈者覆寫單一訊息的目的地。您也可以覆寫用於發佈訊息的基礎 適用於 .NET 的 AWS SDK 用戶端，這在您需要變更角色或憑證的多租用戶應用程式中非常有用，視目的地而定。

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