RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer).
1. Prerequisites
- Install RabbitMQ locally or on a server.
- Default Management UI:
http://localhost:15672
- Default Credentials:
guest/guest
- Default Management UI:
- Install the RabbitMQ.Client package for .NET:
dotnet add package RabbitMQ.Client
2. Architecture Overview
- Shopping Cart API (Producer): Sends a message when a user places an order.
- RabbitMQ: Acts as the broker to hold the message.
- Order API (Consumer): Receives the message and processes the order.
3. RabbitMQ Producer: Shopping Cart API
Step 1: Install RabbitMQ.Client
Ensure the RabbitMQ client library is installed:
dotnet add package RabbitMQ.Client
Step 2: Create the Producer Service
Add a RabbitMQProducer
class to send messages.
RabbitMQProducer.cs:
using RabbitMQ.Client; using System.Text; public class RabbitMQProducer { private readonly string _hostName = "localhost"; private readonly string _queueName = "order-queue"; public void SendMessage(string message) { var factory = new ConnectionFactory() { HostName = _hostName }; using var connection = factory.CreateConnection(); using var channel = connection.CreateModel(); // Declare a queue to ensure it exists channel.QueueDeclare(queue: _queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); var body = Encoding.UTF8.GetBytes(message); // Publish the message channel.BasicPublish(exchange: "", routingKey: _queueName, basicProperties: null, body: body); Console.WriteLine($"[x] Sent: {message}"); } }
Step 3: Add Shopping Cart API Controller
Add a controller to simulate order placement.
ShoppingCartController.cs:
using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class ShoppingCartController : ControllerBase { private readonly RabbitMQProducer _producer; public ShoppingCartController() { _producer = new RabbitMQProducer(); } [HttpPost("place-order")] public IActionResult PlaceOrder([FromBody] Order order) { var orderMessage = $"OrderID: {order.OrderId}, UserID: {order.UserId}, Amount: {order.Amount}"; _producer.SendMessage(orderMessage); return Ok("Order placed successfully!"); } } public class Order { public string OrderId { get; set; } public string UserId { get; set; } public decimal Amount { get; set; } }
Step 4: Test Shopping Cart API
Run the Shopping Cart API and test the endpoint using Postman:
Request:
POST http://localhost:5000/api/shoppingcart/place-order Content-Type: application/json { "OrderId": "12345", "UserId": "User001", "Amount": 299.99 }You should see output:
[x] Sent: OrderID: 12345, UserID: User001, Amount: 299.99
4. RabbitMQ Consumer: Order API
Step 1: Create the Consumer Service
Add a RabbitMQConsumer
class to receive messages.
RabbitMQConsumer.cs:
using RabbitMQ.Client; using RabbitMQ.Client.Events; using System.Text; public class RabbitMQConsumer { private readonly string _hostName = "localhost"; private readonly string _queueName = "order-queue"; public void Start() { var factory = new ConnectionFactory() { HostName = _hostName }; var connection = factory.CreateConnection(); var channel = connection.CreateModel(); // Declare the same queue channel.QueueDeclare(queue: _queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); Console.WriteLine($"[x] Received: {message}"); // Simulate order processing ProcessOrder(message); }; channel.BasicConsume(queue: _queueName, autoAck: true, consumer: consumer); Console.WriteLine("Waiting for messages..."); } private void ProcessOrder(string message) { Console.WriteLine($"Processing Order: {message}"); } }
Step 2: Add Order API Program
Create a simple program to start the consumer.
Program.cs:
public class Program { public static void Main(string[] args) { Console.WriteLine("Order Service Started..."); var consumer = new RabbitMQConsumer(); consumer.Start(); } }
5. Run and Test the Application
Start RabbitMQ:
- Ensure RabbitMQ is running locally on port
5672
and the management UI on15672
.
- Ensure RabbitMQ is running locally on port
Run the Shopping Cart API:
- Start the API and use Postman to place an order.
Run the Order API:
- Start the consumer program.
Expected Output:
In the Order API Console:
[x] Received: OrderID: 12345, UserID: User001, Amount: 299.99 Processing Order: OrderID: 12345, UserID: User001, Amount: 299.99
6. Key Highlights
Benefits of RabbitMQ Integration
- Decoupling:
- Producers and consumers operate independently.
- Reliability:
- Messages are persisted until acknowledged, ensuring no data loss.
- Scalability:
- RabbitMQ can handle large volumes of messages by scaling horizontally.
- Asynchronous Processing:
- Order service processes messages independently, improving responsiveness.
7. Differences Compared to Direct API Calls
8. Conclusion
RabbitMQ is an excellent choice for implementing message-based communication in microservices. By integrating RabbitMQ into a Shopping Cart and Order API, we achieved decoupling, reliability, and scalability.
- Shopping Cart API acts as the producer that sends order messages.
- Order API acts as the consumer that processes the messages asynchronously.
This architecture ensures better fault tolerance, reduced latency, and the ability to scale both services independently.
Ready to implement RabbitMQ in your project? Start exploring it today and make your microservices architecture more robust and scalable!
Comments
Post a Comment