Introduction
Here, we’ll understand how to setting up a RabbitMQ message queue using .NET Core 6 Web API. In this example, we’ll create a simple producer and consumer for sending and receiving messages through RabbitMQ.
Step 1: Install RabbitMQ.Client NuGet Package
In your .NET Core 6 Web API project, open a terminal or package manager console and run the following command to install the RabbitMQ.Client
NuGet package:
dotnet add package RabbitMQ.Client
Step 2: Implement Producer
Create a producer class that sends messages to RabbitMQ:
using RabbitMQ.Client;
using System;
using System.Text;
public class MessageProducer
{
private readonly IConnection _connection;
public MessageProducer(IConnection connection)
{
_connection = connection;
}
public void PublishMessage(string message)
{
using var channel = _connection.CreateModel();
channel.QueueDeclare(queue: "message_queue", durable: false, exclusive: false, autoDelete: false, arguments: null);
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "", routingKey: "message_queue", basicProperties: null, body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
}
Step 3: Implement Consumer
Create a consumer class that receives messages from RabbitMQ:
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
public class MessageConsumer
{
private readonly IConnection _connection;
public MessageConsumer(IConnection connection)
{
_connection = connection;
}
public void ConsumeMessages()
{
using var channel = _connection.CreateModel();
channel.QueueDeclare(queue: "message_queue", durable: false, exclusive: false, autoDelete: false, arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
};
channel.BasicConsume(queue: "message_queue", autoAck: true, consumer: consumer);
}
}
Step 4: Configure Dependency Injection
In your Startup.cs
, configure dependency injection for the producer and consumer:
using RabbitMQ.Client;
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSingleton(factory => new ConnectionFactory
{
HostName = "localhost", // RabbitMQ server hostname
Port = 5672, // Default RabbitMQ port
UserName = "guest",
Password = "guest"
});
services.AddSingleton<IConnection>(sp => sp.GetRequiredService<ConnectionFactory>().CreateConnection());
services.AddSingleton<MessageProducer>();
services.AddSingleton<MessageConsumer>();
}
Step 5: Use Producer and Consumer in Controller
In a controller, you can use the producer to send messages and the consumer to start listening for messages:
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace YourNamespace.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class MessageController : ControllerBase
{
private readonly MessageProducer _messageProducer;
private readonly MessageConsumer _messageConsumer;
public MessageController(MessageProducer messageProducer, MessageConsumer messageConsumer)
{
_messageProducer = messageProducer;
_messageConsumer = messageConsumer;
}
[HttpPost("send")]
public IActionResult SendMessage([FromBody] string message)
{
_messageProducer.PublishMessage(message);
return Ok("Message sent");
}
[HttpGet("receive")]
public IActionResult ReceiveMessages()
{
_messageConsumer.ConsumeMessages();
return Ok("Started consuming messages");
}
}
}
Step 6: Test the Setup
- Start your RabbitMQ server or Docker container if not already running.
- Run your .NET Core 6 Web API.
- Use a tool like Postman to send a POST request to
/api/message/send
with a JSON body containing the message you want to send. - In another terminal, run a GET request to
/api/message/receive
to start the consumer listening for messages. - Observe the output in your Web API terminal and the consumer terminal.
Please note that this example is simplified for demonstration purposes. In a real-world scenario, you’d need to handle more complex cases, error handling, and manage the consumer’s lifecycle properly.