本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
开始使用适用于. 的 Amazon 消息处理框架。 NET
这是适用于预览版中功能的预发布文档。本文档随时可能更改。 |
开始之前,请确保您已完成环境和项目的设置。还要查看SDK特征中的信息。
本主题提供的信息将帮助您开始使用消息处理框架。除了先决条件和配置信息外,还提供了一个教程,向您展示如何实现常见场景。
先决条件和配置
-
您为应用程序提供的凭证必须对应用程序所使用的消息服务和操作具有相应的权限。有关更多信息,请参阅SQSSNS、和各自的开发者指南EventBridge中的安全主题。
-
将 Amazon 消息处理框架用于. NET,则必须将
AWS.Messaging
NuGet包添加到您的项目中。例如: dotnet add package AWS.Messaging
-
该框架与集成。 NET的依赖注入 (DI) 服务容器
。您可以在应用程序启动期间通过调用将其添加 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"); });
教程
本教程演示了如何使用 Amazon 消息处理框架。 NET。它创建了两个应用程序:一个ASP。 NETCore API Minimal在API终端节点收到请求时向Amazon SQS 队列发送消息,以及一个长时间运行的控制台应用程序,用于轮询和处理这些消息。
-
本教程中的说明偏向于. NETCLI,但你可以使用跨平台工具来执行本教程,例如. NETCLI或者微软 Visual Studio。有关工具的信息,请参见安装和配置工具链。
-
本教程假设您使用
[default]
个人资料作为证书。它还假设短期证书具有发送和接收 Amazon SQS 消息的相应权限。有关更多信息,请参阅使用配置SDK身份验证 Amazon和的安全主题SQS。
注意
运行本教程后,您可能会产生SQS发送消息的费用。
步骤
创建 SQS 队列
本教程需要一个SQS队列来向其发送消息和从中接收消息。可以使用 Amazon CLI 或的以下命令之一来创建队列 Amazon Tools for PowerShell。记下返回的队列URL,以便可以在随后的框架配置中指定该队列。
创建并运行发布应用程序
使用以下步骤创建和运行发布应用程序。
-
打开命令提示符或终端。查找或创建操作系统文件夹,可以在该文件夹下创建。 NET项目。
-
在该文件夹中,运行以下命令创建。 NET项目。
dotnet new webapi --name Publisher
-
导航到新项目的文件夹。添加对 Amazon 消息处理框架的依赖关系。 NET。
cd Publisher dotnet add package AWS.Messaging
注意
如果您使用身份 Amazon IAM Identity Center 验证,请务必同时添加
AWSSDK.SSO
和AWSSDK.SSOOIDC
。 -
将中的
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; } } }
-
运行以下命令。这应该会打开一个带有 Swagger UI 的浏览器窗口,允许你探索和测试你的。API
dotnet watch run
<queue URL created earlier>
-
打开
/greeting
端点并选择试用。 -
为消息指定
senderName
和greeting
值,然后选择执行。这会调用你的API,后者发送消息。SQS
创建并运行处理应用程序
使用以下过程创建和运行处理应用程序。
-
打开命令提示符或终端。查找或创建操作系统文件夹,可以在该文件夹下创建。 NET项目。
-
在该文件夹中,运行以下命令创建。 NET项目。
dotnet new console --name Handler
-
导航到新项目的文件夹。添加对 Amazon 消息处理框架的依赖关系。 NET。还要添加
Microsoft.Extensions.Hosting
软件包,它允许您通过配置框架。 NET通用主机。 cd Handler dotnet add package AWS.Messaging dotnet add package Microsoft.Extensions.Hosting
注意
如果您使用身份 Amazon IAM Identity Center 验证,请务必同时添加
AWSSDK.SSO
和AWSSDK.SSOOIDC
。 -
将中的
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()); } } }
-
运行以下命令。这将启动一个长期运行的民意调查员。
dotnet run
<queue URL created earlier>
启动后不久,应用程序将收到本教程第一部分中发送的消息并记录以下消息:
Received message {greeting} from {senderName}
-
按下
Ctrl+C
可停止轮询器。
清理
使用 Amazon CLI 或的以下命令之一 Amazon Tools for PowerShell 删除队列。