Introdução aos tópicos do Barramento de ServiçoGet started with Service Bus topics
Este tutorial cobre as seguintes etapas:This tutorial covers the following steps:
- Escreva um aplicativo de console .NET Core para enviar um conjunto de mensagens ao tópico.Write a .NET Core console application to send a set of messages to the topic.
- Escreva um aplicativo de console .NET Core para receber essas mensagens da assinatura.Write a .NET Core console application to receive those messages from the subscription.
Pré-requisitosPrerequisites
- 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. Ative seus benefícios de assinante do Visual Studio ou do MSDN ou inscreva-se em uma conta gratuita.You can activate your Visual Studio or MSDN subscriber benefits or sign-up for a free account.
- Siga as etapas no início rápido: Use o portal do Azure para criar um tópico e assinaturas do barramento de serviço para o tópico para realizar as seguintes tarefas:Follow steps in the Quickstart: Use the Azure portal to create a Service Bus topic and subscriptions to the topic to do the following tasks:
- Crie um namespace do Barramento de Serviço.Create a Service Bus namespace.
- Obtenha a cadeia de conexão.Get the connection string.
- Crie um tópico no namespace.Create a topic in the namespace.
- Crie uma assinatura para o tópico no namespace.Create one subscription to the topic in the namespace.
- 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.
- NET Core SDK, versão 2.0 ou posterior.NET Core SDK, version 2.0 or later.
Enviar mensagens para o tópicoSend messages to the topic
Para enviar mensagens para o tópico, escreva um aplicativo de console C# usando o Visual Studio.To send messages to the topic, 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
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.
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.
Escrever o código para enviar mensagens para o tópicoWrite code to send messages to the topic
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 followingusing
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;
Dentro de classe
Program
, declare as variáveis a seguir.Within theProgram
class, declare the following variables. Defina a variávelServiceBusConnectionString
para a cadeia de conexão que você obteve ao criar o namespace e definaTopicName
como o nome que você usou ao criar o tópico:Set theServiceBusConnectionString
variable to the connection string that you obtained when creating the namespace, and setTopicName
to the name that you used when creating the topic:const string ServiceBusConnectionString = "<your_connection_string>"; const string TopicName = "<your_topic_name>"; static ITopicClient topicClient;
Substitua o método
Main()
pelo seguinte método asyncMain
que envia mensagens de forma assíncrona usando o método SendMessagesAsync que será adicionado na próxima etapa.Replace theMain()
method with the following asyncMain
method that sends messages asynchronously using the SendMessagesAsync method that you will add in the next step.public static async Task Main(string[] args) { const int numberOfMessages = 10; topicClient = new TopicClient(ServiceBusConnectionString, TopicName); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after sending all the messages."); Console.WriteLine("======================================================"); // Send messages. await SendMessagesAsync(numberOfMessages); Console.ReadKey(); await topicClient.CloseAsync(); }
Diretamente após o método
Main
, adicione o métodoSendMessagesAsync()
a seguir que realiza o trabalho de enviar o número de mensagens especificado pelo métodonumberOfMessagesToSend
(atualmente definido como 10):Directly after theMain
method, add the followingSendMessagesAsync()
method that performs the work of sending the number of messages specified bynumberOfMessagesToSend
(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 topic. 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 topic. await topicClient.SendAsync(message); } } catch (Exception exception) { Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}"); } }
O arquivo Program.cs do remetente deve ficar assim.Here is what your sender 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 { const string ServiceBusConnectionString = "<your_connection_string>"; const string TopicName = "<your_topic_name>"; static ITopicClient topicClient; public static async Task Main(string[] args) { const int numberOfMessages = 10; topicClient = new TopicClient(ServiceBusConnectionString, TopicName); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after sending all the messages."); Console.WriteLine("======================================================"); // Send messages. await SendMessagesAsync(numberOfMessages); Console.ReadKey(); await topicClient.CloseAsync(); } static async Task SendMessagesAsync(int numberOfMessagesToSend) { try { for (var i = 0; i < numberOfMessagesToSend; i++) { // Create a new message to send to the topic 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 topic await topicClient.SendAsync(message); } } catch (Exception exception) { Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}"); } } } }
Execute o programa e verifique o portal do Azure: clique no nome do tópico na janela Visão geral do namespace.Run the program, and check the Azure portal: click the name of your topic in the namespace Overview window. A tela Essentials do tópico é exibida.The topic Essentials screen is displayed. Na assinatura listadas próxima à parte inferior da janela, observe que o valor Contagem de Mensagens da assinatura agora é 10.In the subscription listed near the bottom of the window, notice that the Message Count value for the subscription 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 do tópico aumenta o valor Atual na janela Essentials cada vez que o aplicativo adiciona mensagens ao tópico.Also note that the current size of the topic increments the Current value in the Essentials window each time the app adds messages to the topic.
Receber mensagens da assinaturaReceive messages from the subscription
Para receber as mensagens enviadas, crie outro aplicativo de console do .NET Core e instale o pacote NuGet Microsoft. Azure. ServiceBus , semelhante ao aplicativo 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 assinaturaWrite code to receive messages from the subscription
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 followingusing
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;
Dentro de classe
Program
, declare as variáveis a seguir.Within theProgram
class, declare the following variables. Defina a variávelServiceBusConnectionString
para a cadeia de conexão obtida ao criar o namespace, definaTopicName
como o nome usado ao criar o tópico e definaSubscriptionName
como o nome usado ao criar a assinatura para o tópico:Set theServiceBusConnectionString
variable to the connection string that you obtained when creating the namespace, setTopicName
to the name that you used when creating the topic, and setSubscriptionName
to the name that you used when creating the subscription to the topic:const string ServiceBusConnectionString = "<your_connection_string>"; const string TopicName = "<your_topic_name>"; const string SubscriptionName = "<your_subscription_name>"; static ISubscriptionClient subscriptionClient;
Substitua o método
Main()
pelo seguinte método asyncMain
.Replace theMain()
method with the following asyncMain
method. Ele chama o métodoRegisterOnMessageHandlerAndReceiveMessages()
que será adicionado na próxima etapa.It calls theRegisterOnMessageHandlerAndReceiveMessages()
method that you will add in the next step.public static async Task Main(string[] args) { subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after receiving all the messages."); Console.WriteLine("======================================================"); // Register subscription message handler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); Console.ReadKey(); await subscriptionClient.CloseAsync(); }
Diretamente após o método
Main()
, adicione o método a seguir que registra o manipulador de mensagens e recebe as mensagens enviadas pelo aplicativo do remetente:Directly after theMain()
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. subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); }
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 followingProcessMessagesAsync()
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 subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default). await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed. // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc. // to avoid unnecessary exceptions. }
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; }
O arquivo Program.cs do destinatário deve ficar assim:Here is what your receiver 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 { const string ServiceBusConnectionString = "<your_connection_string>"; const string TopicName = "<your_topic_name>"; const string SubscriptionName = "<your_subscription_name>"; static ISubscriptionClient subscriptionClient; public static async Task Main(string[] args) { subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after receiving all the messages."); Console.WriteLine("======================================================"); // Register subscription message handler and receive messages in a loop RegisterOnMessageHandlerAndReceiveMessages(); Console.ReadKey(); await subscriptionClient.CloseAsync(); } 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 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 processes messages. subscriptionClient.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 subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default). await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed. // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc. // 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. Observe que os valores Contagem de Mensagens e Atuais agora são 0.Notice that the Message Count and Current values are now 0.
Parabéns!Congratulations! Usando a biblioteca .NET padrão, você acabou de criar um tópico e uma assinatura, enviar 10 mensagens e receber essas mensagens.Using the .NET Standard library, you have now created a topic and subscription, sent 10 messages, and received those messages.
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 de Barramento de Serviço permite que usuários se conectem a um namespace de serviço do Barramento de Serviço e administrem 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ó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 topic, queues, subscriptions, relay services, notification hubs and events hubs.
Próximos passosNext steps
Confira o Repositório GitHub do Barramento de Serviço do Microsoft Azure com exemplos que demonstram alguns dos recursos mais avançados de mensagens do Barramento de Serviço.Check out the Service Bus GitHub repository with samples that demonstrate some of the more advanced features of Service Bus messaging.
Comentários
Carregando comentários...