

버전 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-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>

위에 표시된 예제에서는 구성된 메시지 유형에 따라 지원되는 모든 AWS 서비스에 게시할 수 `IMessagePublisher`있는 일반를 사용합니다. 또한 프레임워크는 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();
    }
}
```

SNS 및 EventBridge에 대해 `IEventBridgePublisher` 각각 `ISNSPublisher` 및를 사용하여 동일한 작업을 수행할 수 있습니다.

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

기본적으로 지정된 유형의 메시지는 미리 구성된 대상으로 전송됩니다. 그러나 메시지별 게시자를 사용하여 단일 메시지의 대상을 재정의할 수 있습니다. 메시지를 게시하는 데 사용되는 기본 AWS SDK for .NET 클라이언트를 재정의할 수도 있습니다. 이는 대상에 따라 역할 또는 자격 증명을 변경해야 하는 다중 테넌트 애플리케이션에서 유용할 수 있습니다.

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