この記事のやっていることはそのまま クイック スタート - .NET アプリから Azure Service Bus キューを使用する - Azure Service Bus | Microsoft Learn に書かれており、まさに「ドキュメント読めばわかる」ではあるのですが、ドキュメントを読みながらも意外と前提理解が無かったり人間ならではの都合の良い解釈をしていたりで詰まった箇所があります。
そのためと言っては何なのですが、反省も込めて以下メモ。
はじめに
Service Bus とは:
エンタープライズ メッセージ ブローカーである Azure Service Bus の概要 - Azure Service Bus | Microsoft Learn
Azure Service Bus は、メッセージ キューと、パブリッシュとサブスクライブのトピックを備えたフル マネージド エンタープライズ統合メッセージ ブローカーです。 Service Bus は、アプリケーションとサービスを相互に分離するために使用され、次のような利点があります。
競合する worker 間での作業の負荷分散
サービスやアプリケーションの境界を越えたデータと制御の安全なルーティングおよび転送
高い信頼性を必要とするトランザクション作業の調整
メッセージ、概念的にはこれ。
.NET でメッセージを送受信する
クイック スタート: .NET アプリからメッセージを送受信する に従い試します。
用意するもの
- Azure サブスクリプション
- Visual Studio 2022
Visual Studio を使用している場合、Visual Studio 2022 より前のバージョンには、C# 10 プロジェクトをビルドするために必要なツールとの互換性がありません。
注意書き大事ですね。私は Visual Studio 2017 でなぜか動かないことを小一時間悩んでいました。
Azure Portal からの準備
- 名前空間の作成
- キューの作成 → <キュー名>
- 接続文字列の取得 → <接続文字列>
Visual Studio 2022 からの準備
- (略)\repos\ServiceBusQueueQuickStart\ServiceBusQueueQuickStart.sln
- Install-Package Azure.Messaging.ServiceBus
メッセージを送信する
送信サンプル の通りです。
using Azure.Messaging.ServiceBus;
// the client that owns the connection and can be used to create senders and receivers
ServiceBusClient client;
// the sender used to publish messages to the queue
ServiceBusSender sender;
// number of messages to be sent to the queue
const int numOfMessages = 3;
var clientOptions = new ServiceBusClientOptions()
{
TransportType = ServiceBusTransportType.AmqpWebSockets
};
client = new ServiceBusClient("<接続文字列>", clientOptions);
sender = client.CreateSender("<キュー名>");
// create a batch
using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();
for (int i = 1; i <= numOfMessages; i++)
{
// try adding a message to the batch
if (!messageBatch.TryAddMessage(new ServiceBusMessage($"Message {i}")))
{
// if it is too large for the batch
throw new Exception($"{i} は大きすぎます。");
}
}
try
{
// Use the producer client to send the batch of messages to the Service Bus queue
await sender.SendMessagesAsync(messageBatch);
Console.WriteLine($"{numOfMessages} 件のメッセージが送信されました");
}
finally
{
// Calling DisposeAsync on client types is required to ensure that network
// resources and other unmanaged objects are properly cleaned up.
await sender.DisposeAsync();
await client.DisposeAsync();
}
Console.WriteLine("何かキーを押してください");
Console.ReadKey();
メッセージはこの辺から見られます。
Azure Service Bus Explorer を使用してデータ操作を実行する - Azure Service Bus | Microsoft Learn
メッセージを受信する
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
// the client that owns the connection and can be used to create senders and receivers
ServiceBusClient client;
// the processor that reads and processes messages from the queue
ServiceBusProcessor processor;
// handle received messages
async Task MessageHandler(ProcessMessageEventArgs args)
{
string body = args.Message.Body.ToString();
Console.WriteLine($"Received: {body}");
// complete the message. message is deleted from the queue.
await args.CompleteMessageAsync(args.Message);
}
// handle any errors when receiving messages
Task ErrorHandler(ProcessErrorEventArgs args)
{
Console.WriteLine(args.Exception.ToString());
return Task.CompletedTask;
}
var clientOptions = new ServiceBusClientOptions()
{
TransportType = ServiceBusTransportType.AmqpWebSockets
};
client = new ServiceBusClient("<接続文字列>", clientOptions);
// create a processor that we can use to process the messages
processor = client.CreateProcessor("<キュー名>", new ServiceBusProcessorOptions());
try
{
// add handler to process messages
processor.ProcessMessageAsync += MessageHandler;
// add handler to process any errors
processor.ProcessErrorAsync += ErrorHandler;
// start processing
await processor.StartProcessingAsync();
Console.WriteLine("Wait for a minute and then press any key to end the processing");
Console.ReadKey();
// stop processing
Console.WriteLine("\nStopping the receiver...");
await processor.StopProcessingAsync();
Console.WriteLine("Stopped receiving messages");
}
finally
{
// resources and other unmanaged objects are properly cleaned up.
await processor.DisposeAsync();
await client.DisposeAsync();
}
以下の通り受信する。
無事、エクスプローラーからもメッセージが消えました。
備考
Program を切り替えるにはここ。
あと地味にはまったのは Version なのでこれも記録。
続き:
クイックスタート: .NET を使用してイベントを送受信する - Azure Event Hubs | Microsoft Learn
以上です~