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

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...