

버전 4(V4) AWS SDK for .NET 가 릴리스되었습니다.

변경 사항 해제 및 애플리케이션 마이그레이션에 대한 자세한 내용은 [마이그레이션 주제를](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-consume"></a>

.NET용 AWS 메시지 처리 프레임워크를 사용하면 프레임워크 또는 메시징 서비스 중 하나를 사용하여 [게시](msg-proc-fw-publish.md)된 메시지를 사용할 수 있습니다. 메시지는 다양한 방식으로 사용할 수 있으며, 그 중 일부는 아래에 설명되어 있습니다.

## 메시지 핸들러
<a name="handle-a-message"></a>

메시지를 사용하려면 처리하려는 각 메시지 유형에 대한 `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) 대기열로 이동할 수 있는 대기열에 남아 있습니다.

## 장기 실행 프로세스에서 메시지 처리
<a name="long-running-process"></a>

SQS 대기열 URL`AddSQSPoller`로를 호출하여 대기열을 [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 메시지 폴러 구성
<a name="config-msg-poller"></a>

를 호출할 `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 함수의 메시지 처리
<a name="lambda-functions"></a>

SQS와 Lambda의 통합과 함께 .NET용 AWS 메시지 처리 프레임워크를 사용할 수 있습니다. [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html](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)를 참조하세요.