8. Visual Studio 代码(可选)
az group create -n <your-resource-group-name> -location eastus az servicebus namespace create -g <your-resource-group-name> --name <your-namespace-name> --location eastus az servicebus topic create --g <your-resource-group-name> --namespace-name <your-namespace-name> --name notifications az servicebus topic subscription create --g <your-resource-group-name> --namespace-name <your-namespace-name> --topic-name notifications --name mobile备注:your-resource-group-name和your-namespace-name替换为自己值即可。
.将其余值保留为默认值,然后选择“下一步”。
.确保选中Enlist in .NET Aspire Orchestration并选择Create。
# 堆代码 duidaima.com builder.AddProject<Projects.AspireMessaging_WorkerService>("aspiremessaging.workerservice");完整的文件结构:
dotnet add package Aspire.Azure.Messaging.ServiceBus --prerelease在Razor Pages 项目的Program.csAspireMessaging文件中,添加对扩展方法的调用AddAzureServiceBus:
builder.AddAzureServiceBus("serviceBusConnection");在项目的_appsettings.json文件中AspireMessaging,添加对应的连接信息:
{ "ConnectionStrings": { "serviceBusConnection": "Endpoint=sb://{your_namespace}.servicebus.windows.net/; SharedAccessKeyName=accesskeyname;SharedAccessKey=accesskey" } }备注:将{your_namespace}替换为自己的服务总线空间的名称
app.MapPost("/notify", static async (ServiceBusClient client, string message) => { var sender = client.CreateSender("notifications"); // Create a batch using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync(); if (messageBatch.TryAddMessage( new ServiceBusMessage($"Message {message}")) is false) { // If it's too large for the batch. throw new Exception( $"The message {message} is too large to fit in the batch."); } // Use the producer client to send the batch of // messages to the Service Bus topic. await sender.SendMessagesAsync(messageBatch); Console.WriteLine($"A message has been published to the topic."); })将 .NET Aspire 组件添加到 Worker Service
dotnet add package Aspire.Azure.Messaging.ServiceBus --prerelease在Razor Pages 项目的Program.csAspireMessaging.Worker文件中,添加对扩展方法的调用AddAzureServiceBus:
builder.AddAzureServiceBus("serviceBusConnection");在项目的_appsettings.json文件中AspireMessaging.Worker,添加对应的连接信息:
{ "ConnectionStrings": { "serviceBusConnection": "Endpoint=sb://{your_namespace}.servicebus.windows.net/; SharedAccessKeyName=accesskeyname;SharedAccessKey=accesskey" } }备注:将{your_namespace}替换为自己的服务总线空间的名称
public class Worker( ILogger<Worker> logger, ServiceBusClient client) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var processor = client.CreateProcessor( "notifications", "mobile", new ServiceBusProcessorOptions()); // add handler to process messages processor.ProcessMessageAsync += MessageHandler; // add handler to process any errors processor.ProcessErrorAsync += ErrorHandler; // start processing await processor.StartProcessingAsync(); logger.LogInformation( "Wait for a minute and then press any key to end the processing"); Console.ReadKey(); // stop processing logger.LogInformation("\nStopping the receiver..."); await processor.StopProcessingAsync(); logger.LogInformation("Stopped receiving messages"); } } async Task MessageHandler(ProcessMessageEventArgs args) { string body = args.Message.Body.ToString(); logger.LogInformation("Received: {Body} from subscription.", body); // complete the message. messages is deleted from the subscription. await args.CompleteMessageAsync(args.Message); } // handle any errors when receiving messages Task ErrorHandler(ProcessErrorEventArgs args) { logger.LogError(args.Exception, args.Exception.Message); return Task.CompletedTask; } }最后:在本地运行并测试应用程序