Azure

Getting Began With Azure Service Bus Queues And ASP.NET Core Background Companies

On this article, we’re going to focus on about how one can learn messages from Azure Service Bus Queues. In Half 1 we now have mentioned Azure Service Bus Queues and how one can ship messages into Queues utilizing ASP.NET Core Internet API. Please learn half 1 earlier than beginning this text.

Making a easy utility to ship and obtain messages from the queue

 

Conditions

Overview of the appliance

In Half 1, we now have created an Azure Service Bus Queue from Azure Portal and in addition created ASP.NET Core Internet API to push the message into that queue,

 

 

On this article, we’re going to create a Background Service to obtain a message from Queue. We will probably be utilizing the identical service bus (order-test-asb) and queue (order-queue) that we created in Half 1 for this text.

 

Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services

 

Create Background service to take heed to the message from the Queue

 

Conditions

  • Visual Studio 19(in case you are utilizing .NET Core 3.1)
  • .NET Core 3.1 SDK put in 

 

In ASP.NET Core, background duties might be carried out as hosted companies. A hosted service is a category with background process logic that implements the IHostedService interface. This subject offers three hosted service examples,

  • Background process that runs on a timer.
  • Hosted service that prompts a scoped service. The scoped service can use dependency injection (DI).
  • Queued background duties that run sequentially. 

Together with IHostedService we now have BackgroundService class  which is first launched in ASP.NET Core 3.zero and which is an summary class that already implements the IHostedService Interface. BackgroundService additionally provides an summary technique ExecuteAsync() that returns a Job. So on this article we’re inheriting our class with BackgroundService and implementing an ExecuteAsync() technique.

 

Partly 1 we now have created Order.Internet.Api which is used to ship a message into service bus. Now we’re going to create a hosted background service which is constantly operating and listening to service bus messages,

  • Go to resolution and proper click on on it and choose Add and choose New Venture. 
  • Choose Console App (.Internet Core) and click on on Subsequent.

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services

  • Give title to service and click on on Create.

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services 

  •  Create a brand new file referred to as appsettings.json & add Azure service connection string as under:
    1. {  
    2.  “AppSettings”: {   
    3.    “QueueConnectionString”“<exchange your RootManageSharedAccessKey right here>”,  
    4.    “QueueName”“order-queue”  
    5.  }  
    6. }  
  • First we now have to put in Azure Service Bus NuGet bundle:

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services 

  • So this service must take heed to messages from Azure Service bus we are able to create this as Home windows service. Together with that add the under code to learn to the Appsettings from appsettings.json. So create a category referred to as AppSettings.cs as talked about under:
    1. public class AppSettings  
    2.     {  
    3.         public string QueueConnectionString { getset; }  
    4.         public string QueueName { getset; }  
    5.     }  
  • To configure our service first we have to set up the under packages:

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services 

  • After that add the under code in `program.cs` to configure our service,
    1. class Program  
    2.   {  
    3.       static void Primary(string[] args)  
    4.       {  
    5.           IServiceCollection serviceDescriptors = new ServiceCollection();  
    6.            Host.CreateDefaultBuilder(args)  
    7.               .UseWindowsService()  
    8.               .ConfigureHostConfiguration(configHost =>  
    9.               {  
    10.                   configHost.AddJsonFile(“appsettings.json”, non-compulsory: false, reloadOnChange: true).Construct();  
    11.               })  
    12.               .ConfigureServices((hostContext, companies) =>  
    13.               {  
    14.                   var appSettingsConfig = hostContext.Configuration.GetSection(nameof(AppSettings));  
    15.   
    16.                   companies.AddOptions();  
    17.                   companies.Configure<AppSettings>(appSettingsConfig);  
    18.                   companies.AddSingleton(appSettingsConfig);  
    19.               }).Construct().Run();  
    20.       }  
    21.   }  
  • Now the subsequent half is to create Background service to take heed to messages. So create a category referred to as CraeteOrderHandler.cs and inherit it with class `BackgroundService`. Now override the `ExecuteAsync` and `StopAsync` technique of BackgroundService class.
    1. utilizing System;  
    2. utilizing System.Textual content;  
    3. utilizing System.Threading;  
    4. utilizing System.Threading.Duties;  
    5. utilizing Microsoft.Azure.ServiceBus;  
    6. utilizing Microsoft.Extensions.Internet hosting;  
    7. utilizing Microsoft.Extensions.Choices;  
    8.   
    9. namespace OrderService  
    10. {  
    11.     public class CraeteOrderHandler : BackgroundService  
    12.     {  
    13.         personal readonly AppSettings _appSettings;  
    14.         personal IQueueClient _orderQueueClient;  
    15.   
    16.         public CraeteOrderHandler(IOptions<AppSettings> appSettings)  
    17.         {  
    18.             _appSettings = appSettings?.Worth ?? throw new ArgumentNullException(nameof(appSettings));  
    19.         }  
    20.   
    21.         public async Job Deal with(Message message, CancellationToken cancelToken)  
    22.         {  
    23.             if (message == null)  
    24.                 throw new ArgumentNullException(nameof(message));  
    25.   
    26.             var physique = Encoding.UTF8.GetString(message.Physique);  
    27.             Console.WriteLine($“Create Order Particulars are: {physique}”);  
    28.             await _orderQueueClient.CompleteAsync(message.SystemProperties.LockToken).ConfigureAwait(false);  
    29.         }  
    30.         public digital Job HandleFailureMessage(ExceptionReceivedEventArgs exceptionReceivedEventArgs)  
    31.         {  
    32.             if (exceptionReceivedEventArgs == null)  
    33.                 throw new ArgumentNullException(nameof(exceptionReceivedEventArgs));  
    34.             return Job.CompletedTask;  
    35.         }  
    36.   
    37.         protected override Job ExecuteAsync(CancellationToken stoppingToken)  
    38.         {  
    39.             var messageHandlerOptions = new MessageHandlerOptions(HandleFailureMessage)  
    40.             {  
    41.                 MaxConcurrentCalls = 5,  
    42.                 AutoComplete = false,  
    43.                 MaxAutoRenewDuration = TimeSpan.FromMinutes(10)  
    44.             };  
    45.             _orderQueueClient = new QueueClient(_appSettings.QueueConnectionString, _appSettings.QueueName);  
    46.             _orderQueueClient.RegisterMessageHandler(Deal with, messageHandlerOptions);  
    47.             Console.WriteLine($“{nameof(CraeteOrderHandler)} service has began.”);  
    48.             return Job.CompletedTask;  
    49.         }  
    50.   
    51.         public override async Job StopAsync(CancellationToken stoppingToken)  
    52.         {  
    53.             Console.WriteLine($“{nameof(CraeteOrderHandler)} service has stopped.”);  
    54.             await _orderQueueClient.CloseAsync().ConfigureAwait(false);  
    55.         }  
    56.   
    57.     }  
    58. }  
  • ExecuteAsync() technique calls when service begins so we now have setup a queue consumer object and in addition registered Deal with technique to take heed to messages.
  • In StopAsync() technique we shut the queue consumer connection.
  • In Deal with() technique we simply extract physique from messasge which incorporates our precise knowledge and simply print it in console. 
  • After that permit’s register our hosted service by including under line into `ConfigureServices` technique in Program.cs class.
    1. companies.AddHostedService<CraeteOrderHandler>();  
  • So let’s construct and run the service to take heed to messages. Begin order internet api and ship message to queue which our OrderService going to take heed to.

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services 

    Getting Started With Azure Service Bus Queues And ASP.NET Core Background Services

Conclusion

 

On this Half 2 of Azure Service Bus Queue sequence, we now have realized and carried out Background Service to take heed to messages from Azure service bus queue. 

I actually hope that you just loved this text, share it with buddies and please don’t hesitate to ship me your ideas or feedback.

 

Show More

Related Articles

Leave a Reply

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

Back to top button