Service Bus キューの使用Get started with Service Bus queues

このチュートリアルでは、.NET Core コンソール アプリケーションを作成して、Service Bus キューとの間でメッセージを送受信します。In this tutorial, you create .NET Core console applications to send messages to and receive messages from a Service Bus queue.

前提条件Prerequisites

キューへのメッセージの送信Send messages to the queue

キューにメッセージを送信するために、Visual Studio を使用して C# コンソール アプリケーションを作成します。To send messages to the queue, write a C# console application using Visual Studio.

コンソール アプリケーションの作成Create a console application

Visual Studio を起動し、C# 用の新しいコンソール アプリ (.NET Core) プロジェクトを作成します。Launch Visual Studio and create a new Console App (.NET Core) project for C#. この例では、アプリの名前を CoreSenderApp に します。This example names the app CoreSenderApp.

Service Bus NuGet パッケージの追加Add the Service Bus NuGet package

  1. 新しく作成したプロジェクトを右クリックし、 [NuGet パッケージの管理] を選択します。Right-click the newly created project and select Manage NuGet Packages.

  2. [参照] を選択します。Select Browse. [Microsoft.Azure.ServiceBus] を検索して選択します。Search for and select Microsoft.Azure.ServiceBus.

  3. [インストール] を選択し、インストールが完了したら、NuGet パッケージ マネージャーを閉じます。Select Install to complete the installation, then close the NuGet Package Manager.

    Select a NuGet package

キューにメッセージを送信するコードの作成Write code to send messages to the queue

  1. Program.cs 内の名前空間定義の先頭 (クラス宣言の前) に、次の using ステートメントを追加します。In Program.cs, add the following using statements at the top of the namespace definition, before the class declaration:

    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;
    
  2. Program クラス内で次の変数を宣言します。In the Program class, declare the following variables:

    const string ServiceBusConnectionString = "<your_connection_string>";
    const string QueueName = "<your_queue_name>";
    static IQueueClient queueClient;
    

    名前空間の接続文字列を ServiceBusConnectionString 変数として入力します。Enter your connection string for the namespace as the ServiceBusConnectionString variable. キュー名を入力します。Enter your queue name.

  3. Main() メソッドを次の asyncMain メソッドに置き換えます。Replace the Main() method with the following async Main method. これは次の手順で追加する SendMessagesAsync() メソッドを呼び出して、キューにメッセージを送信します。It calls the SendMessagesAsync() method that you will add in the next step to send messages to the queue.

    public static async Task Main(string[] args)
    {    
        const int numberOfMessages = 10;
        queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
    
        Console.WriteLine("======================================================");
        Console.WriteLine("Press ENTER key to exit after sending all the messages.");
        Console.WriteLine("======================================================");
    
        // Send messages.
        await SendMessagesAsync(numberOfMessages);
    
        Console.ReadKey();
    
        await queueClient.CloseAsync();
    }
    
  4. MainAsync() メソッドのすぐ後に、次の SendMessagesAsync() メソッドを追加します。numberOfMessagesToSend で指定された数 (現時点では 10 に設定) のメッセージを送信する処理が、このメソッドによって実行されます。Directly after the MainAsync() method, add the following SendMessagesAsync() method that does the work of sending the number of messages specified by numberOfMessagesToSend (currently set to 10):

    static async Task SendMessagesAsync(int numberOfMessagesToSend)
    {
        try
        {
            for (var i = 0; i < numberOfMessagesToSend; i++)
            {
                // Create a new message to send to the queue.
                string messageBody = $"Message {i}";
                var message = new Message(Encoding.UTF8.GetBytes(messageBody));
    
                // Write the body of the message to the console.
                Console.WriteLine($"Sending message: {messageBody}");
    
                // Send the message to the queue.
                await queueClient.SendAsync(message);
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
        }
    }
    

Program.cs ファイルは次のようになります。Here is what your Program.cs file should look like.

namespace CoreSenderApp
{
    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;

    class Program
    {
        // Connection String for the namespace can be obtained from the Azure portal under the 
        // 'Shared Access policies' section.
        const string ServiceBusConnectionString = "<your_connection_string>";
        const string QueueName = "<your_queue_name>";
        static IQueueClient queueClient;

        public static async Task Main(string[] args)
        {    
            const int numberOfMessages = 10;
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
    
            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after sending all the messages.");
            Console.WriteLine("======================================================");
    
            // Send messages.
            await SendMessagesAsync(numberOfMessages);
    
            Console.ReadKey();
    
            await queueClient.CloseAsync();
        }

        static async Task SendMessagesAsync(int numberOfMessagesToSend)
        {
            try
            {
                for (var i = 0; i < numberOfMessagesToSend; i++)
                {
                    // Create a new message to send to the queue
                    string messageBody = $"Message {i}";
                    var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                    // Write the body of the message to the console
                    Console.WriteLine($"Sending message: {messageBody}");

                    // Send the message to the queue
                    await queueClient.SendAsync(message);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
        }
    }
}

プログラムを実行し、Azure portal を確認します。Run the program and check the Azure portal.

名前空間の [概要] ウィンドウでキューの名前を選択して、キューの Essentials を表示します。Select the name of your queue in the namespace Overview window to display queue Essentials.

数とサイズが示された受信メッセージ

キューの [アクティブなメッセージ数] の値は、現在 10 です。The Active message count value for the queue is now 10. この値は、メッセージを取得しないまま送信側アプリを実行するたびに 10 ずつ増えます。Each time you run this sender app without retrieving the messages, this value increases by 10.

アプリからキューにメッセージを追加するたびに、キューの最新のサイズによって、 [Essentials][現在] の値が増えます。The current size of the queue increments the CURRENT value in Essentials each time the app adds messages to the queue.

次のセクションでは、これらのメッセージの取得方法について説明します。The next section describes how to retrieve these messages.

キューからメッセージを受け取るReceive messages from the queue

送信したメッセージを受信するには、別のコンソール アプリ (.NET Core) アプリケーションを作成します。To receive the messages you sent, create another Console App (.NET Core) application. 送信側アプリケーションの場合と同様に、Microsoft.Azure.ServiceBus NuGet パッケージをインストールします。Install the Microsoft.Azure.ServiceBus NuGet package, as you did for the sender application.

キューからメッセージを受信するコードの作成Write code to receive messages from the queue

  1. Program.cs 内の名前空間定義の先頭 (クラス宣言の前) に、次の using ステートメントを追加します。In Program.cs, add the following using statements at the top of the namespace definition, before the class declaration:

    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;
    
  2. Program クラス内で次の変数を宣言します。In the Program class, declare the following variables:

    const string ServiceBusConnectionString = "<your_connection_string>";
    const string QueueName = "<your_queue_name>";
    static IQueueClient queueClient;
    

    名前空間の接続文字列を ServiceBusConnectionString 変数として入力します。Enter your connection string for the namespace as the ServiceBusConnectionString variable. キュー名を入力します。Enter your queue name.

  3. Main() メソッドを次のコードに置き換えます。Replace the Main() method with the following code:

    static void Main(string[] args)
    {
        MainAsync().GetAwaiter().GetResult();
    }
    
    static async Task MainAsync()
    {
        queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
    
        Console.WriteLine("======================================================");
        Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
        Console.WriteLine("======================================================");
    
        // Register QueueClient's MessageHandler and receive messages in a loop
        RegisterOnMessageHandlerAndReceiveMessages();
    
        Console.ReadKey();
    
        await queueClient.CloseAsync();
    }
    
  4. MainAsync() メソッドのすぐ後に、次のメソッドを追加します。これは、メッセージ ハンドラーを登録し、送信側アプリケーションによって送信されたメッセージを受信します。Directly after the MainAsync() method, add the following method, which registers the message handler and receives the messages sent by the sender application:

    static void RegisterOnMessageHandlerAndReceiveMessages()
    {
        // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
        var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
        {
            // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
            // Set it according to how many messages the application wants to process in parallel.
            MaxConcurrentCalls = 1,
    
            // Indicates whether the message pump should automatically complete the messages after returning from user callback.
            // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync().
            AutoComplete = false
        };
    
        // Register the function that processes messages.
        queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
    }
    
  5. 先ほどのメソッドのすぐ後に、受信したメッセージを処理する次の ProcessMessagesAsync() メソッドを追加します。Directly after the previous method, add the following ProcessMessagesAsync() method to process the received messages:

    static async Task ProcessMessagesAsync(Message message, CancellationToken token)
    {
        // Process the message.
        Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
    
        // Complete the message so that it is not received again.
        // This can be done only if the queue Client is created in ReceiveMode.PeekLock mode (which is the default).
        await queueClient.CompleteAsync(message.SystemProperties.LockToken);
    
        // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
        // If queueClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
        // to avoid unnecessary exceptions.
    }
    
  6. 最後に、次のメソッドを追加します。例外が発生した場合は、すべてこのメソッドによって処理されます。Finally, add the following method to handle any exceptions that might occur:

    // Use this handler to examine the exceptions received on the message pump.
    static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
    {
        Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
        var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
        Console.WriteLine("Exception context for troubleshooting:");
        Console.WriteLine($"- Endpoint: {context.Endpoint}");
        Console.WriteLine($"- Entity Path: {context.EntityPath}");
        Console.WriteLine($"- Executing Action: {context.Action}");
        return Task.CompletedTask;
    }
    

Program.cs ファイルは次のようになります。Here is what your Program.cs file should look like:

namespace CoreReceiverApp
{
    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;

    class Program
    {
        // Connection String for the namespace can be obtained from the Azure portal under the 
        // 'Shared Access policies' section.
        const string ServiceBusConnectionString = "<your_connection_string>";
        const string QueueName = "<your_queue_name>";
        static IQueueClient queueClient;

        static void Main(string[] args)
        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

            // Register QueueClient's MessageHandler and receive messages in a loop
            RegisterOnMessageHandlerAndReceiveMessages();
 
            Console.ReadKey();

            await queueClient.CloseAsync();
        }

        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Configure the MessageHandler Options in terms of exception handling, number of concurrent messages to deliver etc.
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = 1,

                // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                AutoComplete = false
            };

            // Register the function that will process messages
            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }

        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

            // Complete the message so that it is not received again.
            // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default).
            await queueClient.CompleteAsync(message.SystemProperties.LockToken);

            // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
            // If queueClient has already been Closed, you may chose to not call CompleteAsync() or AbandonAsync() etc. calls 
            // to avoid unnecessary exceptions.
        }

        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}

プログラムを実行し、もう一度ポータルを確認します。Run the program, and check the portal again. [アクティブなメッセージ数][現在] の値は 0 になりました。The Active message count and CURRENT values are now 0.

メッセージが受信された後のキュー

お疲れさまでした。Congratulations! ここではキューを作成して、そのキューに一連のメッセージを送信し、同じキューからそれらのメッセージを受信しました。You've now created a queue, sent a set of messages to that queue, and received those messages from the same queue.

注意

Service Bus リソースは、Service Bus Explorer で管理できます。You can manage Service Bus resources with Service Bus Explorer. Service Bus Explorer を使用すると、ユーザーは簡単に Service Bus 名前空間に接続し、メッセージング エンティティを管理できます。The Service Bus Explorer allows users to easily connect to a Service Bus namespace and administer messaging entities. このツールには、インポート/エクスポート機能や、トピック、キュー、サブスクリプション、リレー サービス、通知ハブ、イベント ハブをテストする機能などの高度な機能が用意されています。The tool provides advanced features like import/export functionality or the ability to test topics, queues, subscriptions, relay services, notification hubs, and event hubs.

次のステップNext steps

Service Bus メッセージングのさらに高度な機能を紹介するサンプルが含まれる GitHub リポジトリを参照してください。Check out our GitHub repository with samples that demonstrate some of the more advanced features of Service Bus messaging.