

 適用於 .NET 的 AWS SDK V3 已進入維護模式。

我們建議您遷移至 [適用於 .NET 的 AWS SDK V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html)。如需如何遷移的其他詳細資訊和資訊，請參閱我們的[維護模式公告](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)。

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

# 使用適用於 .NET 的訊息處理架構來使用 AWS 訊息
使用訊息

.NET AWS 的訊息處理架構可讓您使用架構或其中一個訊息服務來取用已[發佈](msg-proc-fw-publish.md)的訊息。這些訊息可以透過各種方式使用，其中一些如下所述。

## 訊息處理常式


若要取用訊息，請使用您要處理的每個訊息類型的`IMessageHandler`界面來實作訊息處理常式。訊息類型和訊息處理常式之間的映射是在專案啟動中設定。

```
await Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        // Register the AWS Message Processing Framework for .NET
        services.AddAWSMessageBus(builder =>
        {
            // Register an SQS Queue that the framework will poll for messages.
            // NOTE: The URL given below is an example. Use the appropriate URL for your SQS Queue.
            builder.AddSQSPoller("https://sqs.us-west-2.amazonaws.com/012345678910/MyAppProd");

            // Register all IMessageHandler implementations with the message type they should process. 
            // Here messages that match our ChatMessage .NET type will be handled by our ChatMessageHandler
            builder.AddMessageHandler<ChatMessageHandler, ChatMessage>();
        });
    })
    .Build()
    .RunAsync();
```

下列程式碼顯示訊息的範例`ChatMessage`訊息處理常式。

```
public class ChatMessageHandler : IMessageHandler<ChatMessage>
{
    public Task<MessageProcessStatus> HandleAsync(MessageEnvelope<ChatMessage> messageEnvelope, CancellationToken token = default)
    {
        // Add business and validation logic here.
        if (messageEnvelope == null)
        {
            return Task.FromResult(MessageProcessStatus.Failed());
        }

        if (messageEnvelope.Message == null)
        {
            return Task.FromResult(MessageProcessStatus.Failed());
        }

        ChatMessage message = messageEnvelope.Message;

        Console.WriteLine($"Message Description: {message.MessageDescription}");

        // Return success so the framework will delete the message from the queue.
        return Task.FromResult(MessageProcessStatus.Success());
    }
}
```

外部`MessageEnvelope`包含架構使用的中繼資料。其`message`屬性是訊息類型 （在此案例中為 `ChatMessage`)。

您可以返回 `MessageProcessStatus.Success()` ，指出訊息已成功處理，架構將從 Amazon SQS 佇列刪除訊息。傳回 時`MessageProcessStatus.Failed()`，如果已設定，訊息將保留在佇列中，以供再次處理或移至[無效字母佇列](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)。

## 在長時間執行的程序中處理訊息


您可以使用 `AddSQSPoller` SQS 佇列 URL 呼叫 ，以啟動長時間執行[https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice)，以持續輪詢佇列並處理訊息。

```
await Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        // Register the AWS Message Processing Framework for .NET
        services.AddAWSMessageBus(builder =>
        {
            // Register an SQS Queue that the framework will poll for messages.
            // NOTE: The URL given below is an example. Use the appropriate URL for your SQS Queue.
            builder.AddSQSPoller("https://sqs.us-west-2.amazonaws.com/012345678910/MyAppProd", options => 
            {
                // The maximum number of messages from this queue that the framework will process concurrently on this client.
                options.MaxNumberOfConcurrentMessages = 10;

                // The duration each call to SQS will wait for new messages.
                options.WaitTimeSeconds = 20; 
            });

            // Register all IMessageHandler implementations with the message type they should process.
            builder.AddMessageHandler<ChatMessageHandler, ChatMessage>();
        });
    })
    .Build()
    .RunAsync();
```

### 設定 SQS 訊息輪詢器


呼叫 `SQSMessagePollerOptions`時， 可以設定 SQS 訊息輪詢器`AddSQSPoller`。
+ `MaxNumberOfConcurrentMessages` - 佇列中要同時處理的訊息數量上限。預設值為 10。
+ `WaitTimeSeconds` - `ReceiveMessage` SQS 呼叫在傳回前等待訊息抵達佇列的持續時間 （以秒為單位）。如果訊息可用，呼叫會比 更快傳回`WaitTimeSeconds`。預設值為 20。

**訊息可見性逾時處理**

SQS 訊息具有[可見性逾時](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)期間。當一個取用者開始處理指定的訊息時，它會保留在佇列中，但其他取用者會將其隱藏以避免處理超過一次。如果未在再次顯示訊息之前處理和刪除訊息，另一個消費者可能會嘗試處理相同的訊息。

框架會追蹤並嘗試延長目前正在處理之訊息的可見性逾時。您可以在呼叫 `SQSMessagePollerOptions`時，在 上設定此行為`AddSQSPoller`。
+ `VisibilityTimeout` - 從後續擷取請求中隱藏接收訊息的持續時間，以秒為單位。預設值為 30。
+ `VisibilityTimeoutExtensionThreshold` - 當訊息的可見性逾時在即將到期的這幾秒鐘內時，架構會將可見性逾時 （再延長一`VisibilityTimeout`秒鐘） 延長。預設值為 5。
+ `VisibilityTimeoutExtensionHeartbeatInterval` - 架構會在幾秒內檢查`VisibilityTimeoutExtensionThreshold`過期訊息，然後延長可見性逾時的頻率。預設值為 1。

 在下列範例中，架構將每 1 秒檢查一次仍在處理的訊息。對於再次顯示訊息的 5 秒內，框架會自動將每則訊息的可見性逾時延長 30 秒。

```
// NOTE: The URL given below is an example. Use the appropriate URL for your SQS Queue.
builder.AddSQSPoller("https://sqs.us-west-2.amazonaws.com/012345678910/MyAppProd", options => 
{
    options.VisibilityTimeout = 30;
    options.VisibilityTimeoutExtensionThreshold = 5;
    VisibilityTimeoutExtensionHeartbeatInterval = 1;
});
```

## 在 AWS Lambda 函數中處理訊息


您可以使用適用於 .NET AWS 的訊息處理架構搭配 [SQS 與 Lambda 的整合](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html)。這是由 `AWS.Messaging.Lambda`套件提供。請參閱其 [README](https://github.com/aws/aws-dotnet-messaging/blob/main/src/AWS.Messaging.Lambda/README.md) 以開始使用。