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 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

  1. Atualização 3 do Visual Studio 2017 (versão 15.3, 26730.01) ou posterior.Visual Studio 2017 Update 3 (version 15.3, 26730.01) or later.
  2. NET Core SDK, versão 2.0 ou posterior.NET Core SDK, version 2.0 or later.
  3. Uma assinatura do Azure.An Azure subscription. Para concluir este tutorial, você precisa de uma conta do Azure.To complete this tutorial, you need an Azure account. Você pode ativar sua benefícios de assinante do MSDN ou se inscrever para uma conta gratuita.You can activate your MSDN subscriber benefits or sign up for a free account.
  4. Se você não tiver uma fila para trabalhar com, siga as etapas na portal do Azure de uso para criar uma fila do barramento de serviço artigo para criar uma fila.If you don't have a queue to work with, follow steps in the Use Azure portal to create a Service Bus queue article to create a queue.
    1. Leia o quick visão geral do barramento de serviço filas.Read the quick overview of Service Bus queues.
    2. Criar um barramento de serviço namespace.Create a Service Bus namespace.
    3. Obter o cadeia de caracteres de conexão.Get the connection string.
    4. Criar um barramento de serviço fila.Create a Service Bus queue.

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).Launch Visual Studio and create a new Console App (.NET Core) project.

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. Clique na guia Procurar, pesquise por Microsoft.Azure.ServiceBus e depois selecione o item Microsoft.Azure.ServiceBus.Click the Browse tab, search for Microsoft.Azure.ServiceBus, and then select the Microsoft.Azure.ServiceBus item. Clique em Instalar para concluir a instalação e feche essa caixa de diálogo.Click Install to complete the installation, then close this dialog box.

    Selecionar um pacote NuGet

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

  1. Em Program.cs, adicione as seguintes instruções using na parte superior da definição do 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. Dentro de classe Program, declare as variáveis a seguir.Within the Program class, declare the following variables. Defina a variável ServiceBusConnectionString para a cadeia de conexão que você obteve ao criar o namespace e defina QueueName como o nome que você usou ao criar a fila:Set the ServiceBusConnectionString variable to the connection string that you obtained when creating the namespace, and set QueueName to the name that you used when creating the queue:

    const string ServiceBusConnectionString = "<your_connection_string>";
    const string QueueName = "<your_queue_name>";
    static IQueueClient queueClient;
    
  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:

    MainAsync().GetAwaiter().GetResult();
    
  4. Diretamente após Main(), adicione o método MainAsync() assíncrono a seguir que chama o método de envio de mensagens:Directly after Main(), add the following asynchronous MainAsync() method that calls the send messages method:

    static async Task MainAsync()
    {
        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();
    }
    
  5. Diretamente após o método MainAsync(), adicione o método SendMessagesAsync() a seguir que realiza o trabalho de enviar o número de mensagens especificado pelo método numberOfMessagesToSend (atualmente definido como 10):Directly after the MainAsync() method, add the following SendMessagesAsync() method that performs 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}");
        }
    }
    
  6. Seu arquivo Program.cs deve ficar assim.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;
    
            static void Main(string[] args)
            {
                MainAsync().GetAwaiter().GetResult();
            }
    
            static async Task MainAsync()
            {
                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}");
                }
            }
        }
    }
    
  7. Execute o programa e verifique o portal do Azure: clique no nome da fila na janela Visão geral do namespace.Run the program, and check the Azure portal: click the name of your queue in the namespace Overview window. A tela Essentials da fila é exibida.The queue Essentials screen is displayed. Observe que agora o valor de Contagem de Mensagens Ativas da fila é 10.Notice that the Active Message Count value for the queue is now 10. Cada vez que você executa o aplicativo do remetente sem recuperar mensagens (conforme descrito na próxima seção), esse valor aumenta em 10.Each time you run the sender application without retrieving the messages (as described in the next section), this value increases by 10. Observe também que o tamanho atual da fila aumenta o valor Atual na janela Essentials cada vez que o aplicativo adiciona mensagens à fila.Also note that the current size of the queue increments the Current value in the Essentials window each time the app adds messages to the queue.

    Tamanho da mensagem

Receber mensagens da filaReceive messages from the queue

Para receber as mensagens enviadas por você, crie outro aplicativo de console .NET Core e instale o Microsoft.Azure.ServiceBus pacote NuGet, parecido com o aplicativo de remetente anterior.To receive the messages you sent, create another .NET Core console application and install the Microsoft.Azure.ServiceBus NuGet package, similar to the previous sender application.

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

  1. Em Program.cs, adicione as seguintes instruções using na parte superior da definição do 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. Dentro de classe Program, declare as variáveis a seguir.Within the Program class, declare the following variables. Defina a variável ServiceBusConnectionString para a cadeia de conexão que você obteve ao criar o namespace e defina QueueName como o nome que você usou ao criar a fila:Set the ServiceBusConnectionString variable to the connection string that you obtained when creating the namespace, and set QueueName to the name that you used when creating the queue:

    const string ServiceBusConnectionString = "<your_connection_string>";
    const string QueueName = "<your_queue_name>";
    static IQueueClient queueClient;
    
  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:

    MainAsync().GetAwaiter().GetResult();
    
  4. Diretamente após Main(), adicione o método MainAsync() assíncrono a seguir que chama o método RegisterOnMessageHandlerAndReceiveMessages():Directly after Main(), add the following asynchronous MainAsync() method that calls the RegisterOnMessageHandlerAndReceiveMessages() method:

    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 the queue message handler and receive messages in a loop
        RegisterOnMessageHandlerAndReceiveMessages();
    
        Console.ReadKey();
    
        await queueClient.CloseAsync();
    }
    
  5. Diretamente após o método MainAsync(), adicione o método a seguir que registra o manipulador de mensagens e recebe as mensagens enviadas pelo aplicativo do remetente:Directly after the MainAsync() method, add the following method that 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);
    }
    
  6. 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.
    }
    
  7. 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;
    }    
    
  8. O arquivo Program.cs deve ficar assim: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;
            }
        }
    }
    
  9. Execute o programa e verifique o portal novamente.Run the program, and check the portal again. Observe que os valores Contagem de Mensagens Ativas e Atuais agora são 0.Notice that the Active Message Count and Current values are now 0.

    Tamanho da fila

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

Observação

Você pode gerenciar recursos do barramento de serviço com Service Bus Explorer.You can manage Service Bus resources with Service Bus Explorer. O Service Bus Explorer permite aos usuários para se conectar a um namespace do barramento de serviço e administrar entidades de mensagens de uma maneira fácil.The Service Bus Explorer allows users to connect to a Service Bus namespace and administer messaging entities in an easy manner. A ferramenta fornece recursos avançados, como a funcionalidade de importação/exportação ou a capacidade de testar tópico, filas, assinaturas, serviços de retransmissão, os hubs de notificação e os hubs de eventos.The tool provides advanced features like import/export functionality or the ability to test topic, queues, subscriptions, relay services, notification hubs and events hubs.

Próximas etapasNext 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.