Skip to main content

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API


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

  1. Install RabbitMQ locally or on a server.
    • Default Management UI: http://localhost:15672
    • Default Credentials: guest/guest
  2. 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

  1. Start RabbitMQ:

    • Ensure RabbitMQ is running locally on port 5672 and the management UI on 15672.
  2. Run the Shopping Cart API:

    • Start the API and use Postman to place an order.
  3. 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

  1. Decoupling:
    • Producers and consumers operate independently.
  2. Reliability:
    • Messages are persisted until acknowledged, ensuring no data loss.
  3. Scalability:
    • RabbitMQ can handle large volumes of messages by scaling horizontally.
  4. 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

Popular posts from this blog

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...