Run RabbitMQ listener in asp.net core Back
Run RabbitMQ listener in asp.net core
Posted on 14/11/2020 under tech .net microservices rabbitmq

In my previous post, I explained on how to use HostedService to run background task in an asp.net core app. In microservices architecture, often we will need our services to listen to a messaging queue to consume messages as a way to communicate with other services. In this article, I will explain how to use RabbitMQ in an asp.net core to listen to a RabbitMQ queue.
You can refer to the source code here.
Before we begin, do start RabbitMQ in your machine. You can download it or simply pull an image of it using docker.
Create a new asp.net core web project and select api. Install the RabbitMQ client package for your project.
Create a RabbitMQ consumer class that inherits the IHostedService like this:
public class RabbitMQConsumer : IHostedService
{
private IConnection connection;
private IModel channel;
public Task StartAsync(CancellationToken cancellationToken)
{
RegisterRabbitMQConsumer();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
DeRegister();
return Task.CompletedTask;
}
private void RegisterRabbitMQConsumer()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
connection = factory.CreateConnection();
channel = connection.CreateModel();
// Declare the queue channel for listening
channel.QueueDeclare(queue: "rabbit",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
// Create consumer
var consumer = new EventingBasicConsumer(channel);
// Consumer handler for message recieved
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Debug.WriteLine($"Received Message: {message}");
};
// Attach handler to queue
channel.BasicConsume(queue: "rabbit",
autoAck: true,
consumer: consumer);
}
public void DeRegister()
{
connection.Close();
}
}
In the StartAsync() function, we call the RegisterRabbitMQConsumer() function which will connect to RabbitMQ service in localhost and start listening to the queue "Rabbit". Any message consumed from the queue will be printed on the debug window.
Remember to register the service in startup.cs.
// Add HostedService
services.AddHostedService<RabbitMQConsumer>();
Once the app start, the rabbitmq listener will be instantiated and start listening on the declared queue. It's just this simple. Many resources you found out there tends to over complicated this.
However, before we start the app, let's create a background task to continously publish messages to the queue so we can verify that our listener is working. In normal circumstances the publisher will not be in the same app as the listener.
Create a RabbitMQ producer class that inherits the IHostedService like this:
public class RabbitMQProducer : IHostedService
{
private IModel channel;
private Timer _timer;
public RabbitMQProducer()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
var connection = factory.CreateConnection();
channel = connection.CreateModel();
}
public Task StartAsync(CancellationToken cancellationToken)
{
RegisterRabbitMQ();
RegisterTimerPublishEvent();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void RegisterRabbitMQ()
{
// Create a Queue to publish messages to
channel.QueueDeclare(
queue: "rabbit",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null
);
}
private void PublishEvent(object state)
{
// Create message body
string message = $"{DateTime.Now} : Hello World!";
var body = Encoding.UTF8.GetBytes(message);
// Publish message to queue
channel.BasicPublish(
exchange: "",
routingKey: "rabbit",
basicProperties: null,
body: body
);
}
private void RegisterTimerPublishEvent()
{
// Publish to RabbitMQ Queue every 5 seconds
_timer = new Timer(PublishEvent, null, 0, 5000);
}
}
This backgrounds task will simulates a producer pushing message to the queue "Rabbit" every 5 seconds. Remember to register this service in startup.cs as well.
// Add HostedService
services.AddHostedService<RabbitMQProducer>();
Build and run the app now. In the debug output window of visual studio, you will see messages printed by the listener. The rabbitmq listener service is consuming these messages from producer.