适用于 .NET 的 AWS SDK 版本 4(V4)已经发布!
要开始使用新版本的 SDK,请参阅 适用于 .NET 的 AWS SDK(V4)开发人员指南,尤其是关于迁移到版本 4 的主题。
开始使用 AWS Message Processing Framework for .NET
开始之前,请确保您已完成环境和项目的设置。还要查看软件开发工具包功能中的信息。
本主题介绍如何开始使用 Message Processing Framework。除了先决条件和配置信息外,本主题还提供相关教程来展示如何实现常见场景。
先决条件和配置
-
您为应用程序提供的凭证必须具备消息服务及其所用操作的相应权限。有关更多信息,请参阅 SQS、SNS 和 EventBridge 各自开发人员指南中的安全性主题。另请参阅 GitHub 上自述文件
中关于特定权限 的部分。 -
要使用 AWS Message Processing Framework for .NET,您必须将
AWS.MessagingNuGet 软件包添加到您的项目中。例如: 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"); });
教程
本教程演示了如何使用 AWS Message Processing Framework for .NET。它创建了两个应用程序:一个 ASP.NET Core Minimal API,用于在 API 端点收到请求时向 Amazon SQS 队列发送消息;一个长时间运行的控制台应用程序,用于轮询和处理这些消息。
-
本教程中的说明偏好使用 .NET CLI,但您既可以使用 .NET CLI 等跨平台工具,也可以使用 Microsoft Visual Studio 来完成本教程。有关这些工具的信息,请参阅安装和配置工具链。
-
本教程假定您使用
[default]配置文件作为凭证。它还假定短期凭证具有发送和接收 Amazon SQS 消息的相应权限。有关更多信息,请参阅使用 AWS 配置软件开发工具包身份验证和 SQS 的安全性主题。
注意
运行本教程可能会产生 SQS 消息收发费用。
步骤
创建 SQS 队列
本教程需要一个 SQS 队列来向其发送消息和从中接收消息。可以使用 AWS CLI 或 AWS Tools for PowerShell 的以下命令之一来创建队列。记下返回的队列 URL,以便可以在后续框架配置过程中指定它。
创建并运行发布应用程序
按照以下程序创建并运行发布应用程序。
-
打开命令提示符或终端。查找或创建可以在其中创建 .NET 项目的操作系统文件夹。
-
在该文件夹中,运行以下命令以创建 .NET 项目。
dotnet new webapi --name Publisher -
导航到新项目的文件夹。在 AWS Message Processing Framework for .NET 上添加依赖项。
cd Publisher dotnet add package AWS.Messaging注意
如果您使用 AWS 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,该 API 会发送 SQS 消息。
创建并运行处理应用程序
按照以下程序创建并运行处理应用程序。
-
打开命令提示符或终端。查找或创建可以在其中创建 .NET 项目的操作系统文件夹。
-
在该文件夹中,运行以下命令以创建 .NET 项目。
dotnet new console --name Handler -
导航到新项目的文件夹。在 AWS Message Processing Framework for .NET 上添加依赖项。还要添加
Microsoft.Extensions.Hosting软件包,支持您通过 .NET 通用主机配置框架。 cd Handler dotnet add package AWS.Messaging dotnet add package Microsoft.Extensions.Hosting注意
如果您使用 AWS 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停止轮询器。
清理
使用 AWS CLI 或 AWS Tools for PowerShell 的以下命令之一删除队列。