Azure

Microsoft Azure Service Bus-Matter

Introduction

 

In our earlier article, I coated an summary of the service bus, particularly on queue & subjects. Lastly, we noticed how the queue works from the coding perspective.

In case you haven’t examine Service Bus Queues, I extremely suggest you to undergo the article by referring to right here.

 

In case you aren’t utilizing Azure, I’d suggest you go for a free trial utilizing the hyperlink right here.

 

You could find supply code right here.

 

Configuring Matter in Azure Portal

 

Let’s bounce straight into learn how to create a service bus-topic from the Azure portal.

 

I am preferring to stick with the default settings whereas creating the subject i.e. partitioning and duplicate detection are set to disable.

 

Microsoft Azure Service Bus-Topic

 

Microsoft Azure Service Bus-Topic

 

Right here, I am creating two subscriptions, one with Order subscription and one other one with Product subscription. In each subscriptions, we’ve solicited service bus to have the utmost deliveries of messages to five, nevertheless, the remaining settings are set to default. In future articles, we’ll cowl periods, useless lettering, and many others.

 

Microsoft Azure Service Bus-Topic

 

I’ve created two shared entry insurance policies, one for ship and one other one for listening (i.e. we’ll use ship coverage within the writer, whereas the listening coverage for customers (merchandise and orders customers).

 

Coding

 

I’ve created four tasks for this text:

  • ASP.NET Core net api-> Producer
  • 2 Employee Service projects-> 1 for merchandise shopper and one other one for orders shopper.
  • .NET core class library-> Widespread lessons

Add a Microsoft.Azure.ServiceBus NuGet bundle within the producer and shopper (merchandise and orders) tasks

 

Firstly, let’s sort out the Producer performance:

  1. public interface IMessagePublisher {  
  2.     Job PublisherAsync < T > (T request);  
  3. }  
  4. public class MessagePublisher: IMessagePublisher {  
  5.     non-public readonly ITopicClient topicClient;  
  6.     public MessagePublisher(ITopicClient topicClient) {  
  7.         this.topicClient = topicClient;  
  8.     }  
  9.     public async Job PublisherAsync < T > (T request) {  
  10.         var message = new Message {  
  11.             MessageId = Guid.NewGuid().ToString(),  
  12.                 Physique = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request))  
  13.         };  
  14.         message.UserProperties.Add(“MessageType”typeof(T).Identify);  
  15.         await topicClient.SendAsync(message);  
  16.     }  
  17. }  

Message Writer class is just about much like what we’ve carried out within the earlier article. As a substitute of IQueueClient, we’ve to make use of ITopicClient for subject; furthermore, I’ve added MessageId and customized property(MessageType) to the message header. Later, we’ll talk about about why I added customized property intimately.

  1. [Route(“api/[controller]”)]  
  2. [ApiController]  
  3. public class TopicController: ControllerBase {  
  4.     non-public readonly IMessagePublisher messagePublisher;  
  5.     public TopicController(IMessagePublisher messagePublisher) {  
  6.         this.messagePublisher = messagePublisher;  
  7.     }  
  8.       
  9.     [HttpPost(template: “product”)]  
  10.     public async Job SendToProduct([FromBody] Product product) {  
  11.             await messagePublisher.PublisherAsync(product);  
  12.         }  
  13.         [HttpPost(template: “order”)]  
  14.     public async Job SentToOrder([FromBody] Order order) {  
  15.         await messagePublisher.PublisherAsync(order);  
  16.     }  
  17. }  

I’ve created a reasonably simple controller with an HTTP verb as submit for each product and order.

  1. public void ConfigureServices(IServiceCollection companies) {  
  2.     companies.AddControllers();  
  3.     companies.AddSingleton < ITopicClient > (serviceProvider => new TopicClient(connectionString: Configuration.GetValue < string > (“servicebus:connectionstring”), entityPath: Configuration.GetValue < string > (“serviceBus:topicname”)));  
  4.     companies.AddSingleton < IMessagePublisher, MessagePublisher > ();  
  5. }  

Within the startup class, I’ve created a dependency injection for ITopicClient and IMessagePublisher.

  1. {  
  2.     “servicebus”: {  
  3.         “connectionstring”“<ConnectionString Right here>”,  
  4.         “topicname”“<Matter identify right here>”  
  5.     },  
  6.     “Logging”: {  
  7.         “LogLevel”: {  
  8.             “Default”“Info”,  
  9.             “Microsoft”“Warning”,  
  10.             “Microsoft.Internet hosting.Lifetime”“Info”  
  11.         }  
  12.     },  
  13.     “AllowedHosts”“*”  
  14. }  

Listed here are the area lessons outlined in a standard challenge.

  1. public class Order {  
  2.     public int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Identify {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public int Amount {  
  11.         get;  
  12.         set;  
  13.     }  
  14. }  
  15. public class Product {  
  16.     public int Id {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     public string Identify {  
  21.         get;  
  22.         set;  
  23.     }  
  24.     public int Worth {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public string ProductStatus {  
  29.         get;  
  30.         set;  
  31.     }  
  32. }  

Now run the writer with both merchandise or orders. In my case, I am operating with merchandise:

 

Microsoft Azure Service Bus-Topic

 

Now confirm the message rely within the subscription:

 

Microsoft Azure Service Bus-Topic

The great half is that we’re getting the message rely as 1 however wait we’ve the message rely as 1 for orders too. Bizarre, we’re sending the message for merchandise however we’ve obtained a message for orders as properly. Any guess as to why?

 

The reply is as a result of we have no filters for the subject.

 

Let’s perceive what a filter is in subject. Subscribers need to outline which message they need from the subject is known as a filter. Every of the newly created subject subscriptions has an preliminary default subscription rule. If in case, you do not explicitly specify a filter situation for the rule, the utilized filter is 1=1 that permits all messages to be chosen into the subscription.

 

There are 2 varieties of filters in subjects:

  • SQL Filters- SQL filters maintain SQL like conditional expressions in opposition to system and consumer properties(customized properties). Right here is the reply, why we used customized property within the message.
  • Correlational Filters- Correlation filters are used to match in opposition to a number of message techniques or consumer properties.

In these articles, we’ll be targeted on each filters.

 

Microsoft Azure Service Bus-Topic

 

By default, the default filter is utilized i.e. 1=1 or it is going to settle for all of the incoming messages.

 

Let’s add a brand new filter:

 

Microsoft Azure Service Bus-Topic

 

For merchandise, I’ve used the SQL filter. With a view to obtain a message from the subject, I’ve set MessageType=’Product’

 

Microsoft Azure Service Bus-Topic

 

For orders, I’ve used a Correlation filter. I’ve specified the customized properties to obtain a message from the subject.

 

Now run the postman and see the end result. Now I am operating for merchandise:

 

Microsoft Azure Service Bus-Topic

Right here we go, the message has been obtained for product subscription. The writer appears to be working effective.

 

Now, let’s transfer our deal with each the customers. First, let’s start with merchandise shopper.

  1. public static IHostBuilder CreateHostBuilder(string[] args) =>  
  2. Host.CreateDefaultBuilder(args)  
  3. .ConfigureServices((hostContext, companies) =>  
  4. {  
  5.    companies.AddHostedService<Employee>();  
  6.    companies.AddSingleton<ISubscriptionClient>(serviceProvider => new SubscriptionClient(  
  7.    connectionString: “<ConnectionString Right here”,  
  8.    topicPath: “<Matter Identify right here>”, subscriptionName: “ProductSubscription”));  
  9. });  

We now have created dependency injection for ISubscriptionClient by passing connection string, subject identify and subscription identify.

 

Word

It’s a must to use hear key of the shared entry coverage for the connection string.

  1. public class Employee: BackgroundService {  
  2.         non-public readonly ILogger < Employee > _logger;  
  3.         non-public readonly ISubscriptionClient subscriptionClient;  
  4.         public Employee(ILogger < Employee > logger, ISubscriptionClient subscriptionClient) {  
  5.             _logger = logger;  
  6.             this.subscriptionClient = subscriptionClient;  
  7.         }  
  8.         protected override async Job ExecuteAsync(CancellationToken stoppingToken) {  
  9.             subscriptionClient.RegisterMessageHandler((message, token) => {  
  10.                 _logger.LogInformation($ “message id:{message.MessageId}”);  
  11.                 _logger.LogInformation($ “message physique:{Encoding.UTF8.GetString( message.Physique)}”);  
  12.                 var product = JsonConvert.DeserializeObject < Widespread.Product > (Encoding.UTF8.GetString(message.Physique));  
  13.                   
  14.                 return subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);  
  15.             }, new MessageHandlerOptions(ex => {  
  16.                 _logger.LogError(ex.Exception, ex.Exception.Message);  
  17.                 return Job.FromException(ex.Exception);  
  18.             }) {  
  19.                 AutoComplete = false,  
  20.                     MaxConcurrentCalls = 1  
  21.             });  
  22.         }  

You might want to register the message handler with a view to obtain messages from the subject. Within the above snippet, we’re changing the message physique from bytes to product object. Do not forget to specify AutoComplete=false different you’ll find yourself with an exception.

 

Equally, we’ve to create for Order subscription as properly. There are completely no change when it comes to code apart from specifying subscription identify in this system class.

  1. public static IHostBuilder CreateHostBuilder(string[] args) =>  
  2. Host.CreateDefaultBuilder(args)  
  3. .ConfigureServices((hostContext, companies) =>  
  4. {  
  5.    companies.AddHostedService<Employee>();  
  6.    companies.AddSingleton<ISubscriptionClient>(serviceProvider => new SubscriptionClient(  
  7.    connectionString: “<ConnectionString Right here”,  
  8.    topicPath: “<Matter Identify right here>”, subscriptionName: “ProductSubscription”));  
  9. });  

Lastly, we’ve managed to place all of the code modifications in place. Run the appliance and confirm for each the merchandise and orders.

 

I hope you favored the article. In case you discover the article fascinating, then kindly like and share it.

Tags
Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close