Consuming RabbitMQ Messages In ASP.NET Core

In this article, I’d like to present how to consume the RabbitMQ message via BackgroundService in ASP.NET Core.

Background tasks play a very important role when we are building a distributed system. The most common scenario is consuming the service bus's message. In this article, I'd like to present how to consume the RabbitMQ message via BackgroundService in ASP.NET Core.

Run RabbitMQ Host

 
We should set up an instance of RabbitMQ. The fastest way is to use Docker. 
  1. docker run -p 5672:5672 -p 15672:15672 rabbitmq:management   
After running the Docker container, we are able to view the management page via http://localhost:15672.
 
 Consuming RabbitMQ Messages In ASP.NET Core

 
Setup the BackgroundService

 
Here, we create a new class named ConsumeRabbitMQHostedService that is inherited from BackgroundService.
 
BackgroundService is a base class for implementing a long-running IHostedService. It provides the main work needed to set up the background task.
 
Here is an example to demonstrate how to consume RabbitMQ messages.
  1. public class ConsumeRabbitMQHostedService : BackgroundService  
  2. {  
  3.     private readonly ILogger _logger;  
  4.     private IConnection _connection;  
  5.     private IModel _channel;  
  6.   
  7.     public ConsumeRabbitMQHostedService(ILoggerFactory loggerFactory)  
  8.     {  
  9.         this._logger = loggerFactory.CreateLogger<ConsumeRabbitMQHostedService>();  
  10.         InitRabbitMQ();  
  11.     }  
  12.   
  13.     private void InitRabbitMQ()  
  14.     {  
  15.         var factory = new ConnectionFactory { HostName = "localhost" };  
  16.   
  17.         // create connection  
  18.         _connection = factory.CreateConnection();  
  19.   
  20.         // create channel  
  21.         _channel = _connection.CreateModel();  
  22.   
  23.         _channel.ExchangeDeclare("demo.exchange", ExchangeType.Topic);  
  24.         _channel.QueueDeclare("demo.queue.log"falsefalsefalsenull);  
  25.         _channel.QueueBind("demo.queue.log""demo.exchange""demo.queue.*"null);  
  26.         _channel.BasicQos(0, 1, false);  
  27.   
  28.         _connection.ConnectionShutdown += RabbitMQ_ConnectionShutdown;  
  29.     }  
  30.   
  31.     protected override Task ExecuteAsync(CancellationToken stoppingToken)  
  32.     {  
  33.         stoppingToken.ThrowIfCancellationRequested();  
  34.   
  35.         var consumer = new EventingBasicConsumer(_channel);  
  36.         consumer.Received += (ch, ea) =>  
  37.         {  
  38.             // received message  
  39.             var content = System.Text.Encoding.UTF8.GetString(ea.Body);  
  40.   
  41.             // handle the received message  
  42.             HandleMessage(content);  
  43.             _channel.BasicAck(ea.DeliveryTag, false);  
  44.         };  
  45.   
  46.         consumer.Shutdown += OnConsumerShutdown;  
  47.         consumer.Registered += OnConsumerRegistered;  
  48.         consumer.Unregistered += OnConsumerUnregistered;  
  49.         consumer.ConsumerCancelled += OnConsumerConsumerCancelled;  
  50.   
  51.         _channel.BasicConsume("demo.queue.log"false, consumer);  
  52.         return Task.CompletedTask;  
  53.     }  
  54.   
  55.     private void HandleMessage(string content)  
  56.     {  
  57.         // we just print this message   
  58.         _logger.LogInformation($"consumer received {content}");  
  59.     }  
  60.       
  61.     private void OnConsumerConsumerCancelled(object sender, ConsumerEventArgs e)  {  }  
  62.     private void OnConsumerUnregistered(object sender, ConsumerEventArgs e) {  }  
  63.     private void OnConsumerRegistered(object sender, ConsumerEventArgs e) {  }  
  64.     private void OnConsumerShutdown(object sender, ShutdownEventArgs e) {  }  
  65.     private void RabbitMQ_ConnectionShutdown(object sender, ShutdownEventArgs e)  {  }  
  66.   
  67.     public override void Dispose()  
  68.     {  
  69.         _channel.Close();  
  70.         _connection.Close();  
  71.         base.Dispose();  
  72.     }  
  73. }  

Configure Services

 
We should configure this hosted service with the background task logic in ConfigureServices method.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     // others ...  
  4.       
  5.     services.AddHostedService<ConsumeRabbitMQHostedService>();  
  6. }   

 

Result

 
After running this app, we may get the following output in the terminal.
 
Consuming RabbitMQ Messages In ASP.NET Core
 
Turning to the Management UI of RabbitMQ, we find that it creates a new exchange and a new queue.
Consuming RabbitMQ Messages In ASP.NET Core
The next time we try to publish a message to show the background task is running well, we get the following result.
 
Consuming RabbitMQ Messages In ASP.NET Core
 
All things went well!
 

Summary

 
This article showed you how to consume RabbitMQ message via BackgroundService in ASP.NET Core. I hope this will help you!