

的版本 4 (V4) 适用于 .NET 的 Amazon SDK 已经发布！

有关重大更改和迁移应用程序的信息，请参阅[迁移主题](https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html)

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 开始使用适用于.NET 的 Amazon 消息处理框架
<a name="msg-proc-fw-get-started"></a>

在开始之前，请确保您已经[设置了环境](net-dg-config.md)并[配置了项目](configuring-the-sdk.md)。还要查看[使用 SDK](net-dg-sdk-features.md)中的信息。

本主题提供的信息将帮助您开始使用消息处理框架。除了先决条件和配置信息外，还提供了一个教程，向您展示如何实现常见场景。

## 先决条件和配置
<a name="mpf-get-started-prereq"></a>
+ 您为应用程序提供的凭证必须对应用程序所使用的消息服务和操作具有相应的权限。有关更多信息，请参阅 [SQS、[SN](https://docs.amazonaws.cn/sns/latest/dg/security-iam.html) S](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-authentication-and-access-control.html) 的安全主题及其各自[EventBridge](https://docs.amazonaws.cn/eventbridge/latest/userguide/eb-iam.html)的开发者指南。另请参阅 [README](https://github.com/aws/aws-dotnet-messaging/) 文件中讨论特定[权限 GitHub ](https://github.com/aws/aws-dotnet-messaging/blob/main/README.md#permissions)的部分。
+ 要使用适用于.NET 的 Amazon 消息处理框架，必须将该[https://www.nuget.org/packages/AWS.Messaging](https://www.nuget.org/packages/AWS.Messaging) NuGet包添加到您的项目中。例如：

  ```
  dotnet add package AWS.Messaging
  ```
+ 该框架与.NET 的[依赖注入 (DI) 服务容器集](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection)成。您可以在应用程序启动期间通过调用将其添加`AddAWSMessageBus`到 DI 容器来配置框架。

  ```
  var builder = WebApplication.CreateBuilder(args);
  
  // Register the AWS Message Processing Framework for .NET
  builder.Services.AddAWSMessageBus(builder =>
  {
      // Register that you'll publish messages of type ChatMessage to an existing queue
      builder.AddSQSPublisher<ChatMessage>("https://sqs.us-west-2.amazonaws.com/012345678910/MyAppProd");
  });
  ```

## 教程
<a name="mpf-get-started-tutorial"></a>

本教程演示如何使用适用于.NET 的 Amazon 消息处理框架。它创建了两个应用程序：一个 ASP.NET Core Minimal API，用于在 API 终端节点收到请求时向 Amazon SQS 队列发送消息，以及一个长时间运行的控制台应用程序，用于轮询和处理这些消息。
+ 本教程中的说明偏向于.NET CLI，但你可以使用跨平台工具（例如.NET CLI 或 Microsoft Visual Studio）来执行本教程。有关工具的信息，请参见[安装和配置您的工具链 适用于 .NET 的 Amazon SDK](net-dg-dev-env.md)。
+ 本教程假设您正在使用`[default]`个人资料作为凭证。它还假设短期证书具有发送和接收 Amazon SQS 消息的相应权限。有关更多信息，请参阅[使用进行身份验证 适用于 .NET 的 Amazon SDK Amazon](creds-idc.md)和 S [QS](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-authentication-and-access-control.html) 的安全主题。

**注意**  
运行本教程后，您可能会产生 SQS 消息传送费用。

### 步骤
<a name="mpf-tutorial-steps"></a>
+ [创建 SQS 队列](#mpf-tutorial-queue)
+ [创建并运行发布应用程序](#mpf-tutorial-publish)
+ [创建并运行处理应用程序](#mpf-tutorial-handle)
+ [清理](#mpf-tutorial-cleanup)

### 创建 SQS 队列
<a name="mpf-tutorial-queue"></a>

本教程需要一个 SQS 队列来向其发送消息和从中接收消息。可以使用 Amazon CLI 或的以下命令之一来创建队列 Amazon Tools for PowerShell。记下返回的队列 URL，以便可以在随后的框架配置中指定它。

------
#### [ Amazon CLI ]

```
aws sqs create-queue --queue-name DemoQueue
```

------
#### [ Amazon Tools for PowerShell ]

```
New-SQSQueue -QueueName DemoQueue
```

------

### 创建并运行发布应用程序
<a name="mpf-tutorial-publish"></a>

使用以下步骤创建和运行发布应用程序。

1. 打开命令提示符或终端。查找或创建可以在其中创建 .NET 项目的操作系统文件夹。

1. 在该文件夹中，运行以下命令以创建 .NET 项目。

   ```
   dotnet new webapi --name Publisher
   ```

1. 导航到新项目的文件夹。添加对.NET Amazon 消息处理框架的依赖关系。

   ```
   cd Publisher
   dotnet add package AWS.Messaging
   ```
**注意**  
如果您使用身份 Amazon IAM Identity Center 验证，请务必同时添加`AWSSDK.SSO`和`AWSSDK.SSOOIDC`。

1. 将中的`Program.cs`代码替换为以下代码。

   ```
   using AWS.Messaging;
   using Microsoft.AspNetCore.Mvc;
   using Publisher;
   
   var builder = WebApplication.CreateBuilder(args);
   
   // Add services to the container.
   // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle.
   builder.Services.AddEndpointsApiExplorer();
   builder.Services.AddSwaggerGen();
   
   
   // Configure the AWS Message Processing Framework for .NET.
   builder.Services.AddAWSMessageBus(builder =>
   {
       // Check for input SQS URL.
       // The SQS URL should be passed as a command line argument or set in the Debug launch profile.
       if ((args.Length == 1) && (args[0].Contains("https://sqs.")))
       {
           // Register that you'll publish messages of type GreetingMessage:
           // 1. To a specified queue.
           // 2. Using the message identifier "greetingMessage", which will be used
           //    by handlers to route the message to the appropriate handler.
           builder.AddSQSPublisher<GreetingMessage>(args[0], "greetingMessage");
       }
       // You can map additional message types to queues or topics here as well.
   });
   var app = builder.Build();
   
   
   // Configure the HTTP request pipeline.
   if (app.Environment.IsDevelopment())
   {
       app.UseSwagger();
       app.UseSwaggerUI();
   }
   
   app.UseHttpsRedirection();
   
   // Create an API Endpoint that receives GreetingMessage objects
   // from the caller and then sends them as an SQS message.
   app.MapPost("/greeting", async ([FromServices] IMessagePublisher publisher, Publisher.GreetingMessage message) =>
       {
           return await PostGreeting(message, publisher);
       })
   .WithName("SendGreeting")
   .WithOpenApi();
   
   app.Run();
   
   public partial class Program
   {
       /// <summary>
       /// Endpoint for posting a greeting message.
       /// </summary>
       /// <param name="greetingMessage">The greeting message.</param>
       /// <param name="messagePublisher">The message publisher.</param>
       /// <returns>Async task result.</returns>
       public static async Task<IResult> PostGreeting(GreetingMessage greetingMessage,
           IMessagePublisher messagePublisher)
       {
           if (greetingMessage.SenderName == null || greetingMessage.Greeting == null)
           {
               return Results.BadRequest();
           }
   
           // Publish the message to the queue configured above.
           await messagePublisher.PublishAsync(greetingMessage);
   
           return Results.Ok();
       }
   }
   
   namespace Publisher
   {
       /// <summary>
       /// This class represents the message contents.
       /// </summary>
       public class GreetingMessage
       {
           public string? SenderName { get; set; }
           public string? Greeting { get; set; }
       }
   }
   ```

1. 运行以下命令。这应该会打开一个带有 Swagger UI 的浏览器窗口，允许你浏览和测试你的 API。

   ```
   dotnet watch run <queue URL created earlier>
   ```

1. 打开`/greeting`端点并选择**试用**。

1. 为消息指定`senderName`和`greeting`值，然后选择**执行**。这会调用你的 API，它会发送 SQS 消息。

### 创建并运行处理应用程序
<a name="mpf-tutorial-handle"></a>

使用以下过程创建和运行处理应用程序。

1. 打开命令提示符或终端。查找或创建可以在其中创建 .NET 项目的操作系统文件夹。

1. 在该文件夹中，运行以下命令以创建 .NET 项目。

   ```
   dotnet new console --name Handler
   ```

1. 导航到新项目的文件夹。添加对.NET Amazon 消息处理框架的依赖关系。还要添加`Microsoft.Extensions.Hosting`软件包，它允许您通过 [.NET 通用主机](https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host)配置框架。

   ```
   cd Handler
   dotnet add package AWS.Messaging
   dotnet add package Microsoft.Extensions.Hosting
   ```
**注意**  
如果您使用身份 Amazon IAM Identity Center 验证，请务必同时添加`AWSSDK.SSO`和`AWSSDK.SSOOIDC`。

1. 将中的`Program.cs`代码替换为以下代码。

   ```
   using AWS.Messaging;
   using Handler;
   using Microsoft.Extensions.DependencyInjection;
   using Microsoft.Extensions.Hosting;
   
   var builder = Host.CreateDefaultBuilder(args);
   
   builder.ConfigureServices(services =>
   {
       // Register the AWS Message Processing Framework for .NET.
       services.AddAWSMessageBus(builder =>
       {
           // Check for input SQS URL.
           // The SQS URL should be passed as a command line argument or set in the Debug launch profile.
           if ((args.Length == 1) && (args[0].Contains("https://sqs.")))
           {
               // Register you'll poll the following queue.
               builder.AddSQSPoller(args[0]);
   
               // And that messages of type "greetingMessage" should be:
               // 1. Deserialized as GreetingMessage objects.
               // 2. Which are then passed to GreetingMessageHandler.
               builder.AddMessageHandler<GreetingMessageHandler, GreetingMessage>("greetingMessage");
   
           }
           // You can add additional message handlers here, using different message types. 
       });
   });
   
   var host = builder.Build();
   await host.RunAsync();
   
   namespace Handler
   {
       /// <summary>
       /// This class represents the message contents.
       /// </summary>
       public class GreetingMessage
       {
           public string? SenderName { get; set; }
           public string? Greeting { get; set; }
       }
   
       /// <summary>
       /// This handler is invoked each time you receive the message.
       /// </summary>
       public class GreetingMessageHandler : IMessageHandler<GreetingMessage>
       {
           public Task<MessageProcessStatus> HandleAsync(
               MessageEnvelope<GreetingMessage> messageEnvelope,
               CancellationToken token = default)
           {
               Console.WriteLine(
                   $"Received message {messageEnvelope.Message.Greeting} from {messageEnvelope.Message.SenderName}");
               return Task.FromResult(MessageProcessStatus.Success());
           }
       }
   }
   ```

1. 运行以下命令。这将启动一个长期运行的民意调查员。

   ```
   dotnet run <queue URL created earlier>
   ```

   启动后不久，应用程序将收到本教程第一部分中发送的消息并记录以下消息：

   ```
   Received message {greeting} from {senderName}
   ```

1. 按下`Ctrl+C`可停止轮询器。

### 清理
<a name="mpf-tutorial-cleanup"></a>

使用 Amazon CLI 或的以下命令之一 Amazon Tools for PowerShell 删除队列。

------
#### [ Amazon CLI ]

```
aws sqs delete-queue --queue-url "<queue URL created earlier>"
```

------
#### [ Amazon Tools for PowerShell ]

```
Remove-SQSQueue -QueueUrl "<queue URL created earlier>"
```

------