Introdução às filas do Barramento de ServiçoGet started with Service Bus queues

Neste tutorial, você cria aplicativos de console .NET Core para enviar mensagens e receber mensagens de uma fila do barramento de serviço.In this tutorial, you create .NET Core console applications to send messages to and receive messages from a Service Bus queue.

Pré-requisitosPrerequisites

Enviar mensagens para a filaSend messages to the queue

Para enviar mensagens para a fila, escreva um aplicativo de console em C# usando o Visual Studio.To send messages to the queue, write a C# console application using Visual Studio.

Criar um aplicativo de consoleCreate a console application

Inicie o Visual Studio e crie um novo projeto de aplicativo de console (.NET Core) para C#o.Launch Visual Studio and create a new Console App (.NET Core) project for C#. Este exemplo nomeia o aplicativo CoreSenderApp.This example names the app CoreSenderApp.

Adicionar o pacote NuGet do Barramento de ServiçoAdd the Service Bus NuGet package

  1. Clique com o botão direito do mouse no projeto recém-criado e selecione Gerenciar Pacotes NuGet.Right-click the newly created project and select Manage NuGet Packages.

  2. Selecione Procurar.Select Browse. Pesquise e selecione Microsoft. Azure. ServiceBus .Search for and select Microsoft.Azure.ServiceBus.

  3. Selecione instalar para concluir a instalação e feche o Gerenciador de pacotes NuGet.Select Install to complete the installation, then close the NuGet Package Manager.

    Selecionar um pacote NuGet

Escreva o código para enviar mensagens para a filaWrite code to send messages to the queue

  1. No Program.cs, adicione as instruções de using a seguir na parte superior da definição de namespace, antes da declaração de classe: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. Na classe Program, declare as seguintes variáveis:In the Program class, declare the following variables:

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

    Insira sua cadeia de conexão para o namespace como a variável ServiceBusConnectionString.Enter your connection string for the namespace as the ServiceBusConnectionString variable. Insira o nome da fila.Enter your queue name.

  3. Substitua o método Main() pelo seguinte método async Main.Replace the Main() method with the following async Main method. Ele chama o método SendMessagesAsync que será adicionado na próxima etapa para enviar mensagens para a fila.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. Diretamente após o método MainAsync(), adicione o seguinte método SendMessagesAsync() que faz o trabalho de enviar o número de mensagens especificado por numberOfMessagesToSend (atualmente definido como 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}");
        }
    }
    

Veja como deve ser o seu arquivo 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}");
            }
        }
    }
}

Execute o programa e verifique o portal do Azure.Run the program and check the Azure portal.

Selecione o nome da sua fila na janela visão geral do namespace para exibir a fila Essentials.Select the name of your queue in the namespace Overview window to display queue Essentials.

Mensagens recebidas com contagem e tamanho

O valor de contagem de mensagens ativas para a fila agora é 10.The Active message count value for the queue is now 10. Cada vez que você executar esse aplicativo de remetente sem recuperar as mensagens, esse valor aumentará em 10.Each time you run this sender app without retrieving the messages, this value increases by 10.

O tamanho atual da fila incrementa o valor atual no Essentials cada vez que o aplicativo adiciona mensagens à fila.The current size of the queue increments the CURRENT value in Essentials each time the app adds messages to the queue.

A próxima seção descreve como recuperar essas mensagens.The next section describes how to retrieve these messages.

Receber mensagens da filaReceive messages from the queue

Para receber as mensagens enviadas, crie outro aplicativo de aplicativo de console (.NET Core) .To receive the messages you sent, create another Console App (.NET Core) application. Instale o pacote NuGet Microsoft. Azure. ServiceBus , como você fez para o aplicativo do remetente.Install the Microsoft.Azure.ServiceBus NuGet package, as you did for the sender application.

Escrever código para receber mensagens da filaWrite code to receive messages from the queue

  1. No Program.cs, adicione as instruções de using a seguir na parte superior da definição de namespace, antes da declaração de classe: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. Na classe Program, declare as seguintes variáveis:In the Program class, declare the following variables:

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

    Insira sua cadeia de conexão para o namespace como a variável ServiceBusConnectionString.Enter your connection string for the namespace as the ServiceBusConnectionString variable. Insira o nome da fila.Enter your queue name.

  3. Substitua o conteúdo padrão de Main() com a seguinte linha de código:Replace the default contents of Main() with the following line of code:

    public static async Task Main(string[] args)
    {    
        queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
    
        Console.WriteLine("======================================================");
        Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
        Console.WriteLine("======================================================");
    
        // Register the queue message handler and receive messages in a loop
        RegisterOnMessageHandlerAndReceiveMessages();
    
        Console.ReadKey();
    
        await queueClient.CloseAsync();
    }
    
  4. Diretamente após o método MainAsync(), adicione o seguinte método, que registra o manipulador de mensagens e recebe as mensagens enviadas pelo aplicativo do remetente: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. Diretamente após o método anterior, adicione o método ProcessMessagesAsync() a seguir para processar as mensagens recebidas: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. Por fim, adicione o seguinte método para lidar com qualquer exceção que possa ocorrer: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;
    }
    

Veja como o arquivo Program.cs deve ser: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;
        }
    }
}

Execute o programa e verifique o portal novamente.Run the program, and check the portal again. A contagem de mensagens ativas e os valores atuais agora são 0.The Active message count and CURRENT values are now 0.

Fila após as mensagens terem sido recebidas

Parabéns!Congratulations! Agora você criou uma fila, enviou um conjunto de mensagens para essa fila e recebeu essas mensagens da mesma fila.You've now created a queue, sent a set of messages to that queue, and received those messages from the same queue.

Observação

É possível gerenciar os recursos do Barramento de Serviço com o Gerenciador de Barramento de Serviço.You can manage Service Bus resources with Service Bus Explorer. O Gerenciador do barramento de serviço permite que os usuários se conectem facilmente a um namespace do barramento de serviço e administrem entidades de mensagens.The Service Bus Explorer allows users to easily connect to a Service Bus namespace and administer messaging entities. A ferramenta fornece recursos avançados como a funcionalidade de importação/exportação ou a capacidade de testar tópicos, filas, assinaturas, serviços de retransmissão, hubs de notificação e hubs de eventos.The tool provides advanced features like import/export functionality or the ability to test topics, queues, subscriptions, relay services, notification hubs, and event hubs.

Próximos passosNext steps

Confira nosso Repositório GitHub com exemplos que demonstram alguns dos recursos mais avançados de mensagens do Barramento de Serviço.Check out our GitHub repository with samples that demonstrate some of the more advanced features of Service Bus messaging.