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

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."...

20+ LINQ Concepts with .Net Code

LINQ   (Language Integrated Query) is one of the most powerful features in .NET, providing a unified syntax to query collections, databases, XML, and other data sources. Below are 20+ important LINQ concepts, their explanations, and code snippets to help you understand their usage. 1.  Where  (Filtering) The  Where()  method is used to filter a collection based on a given condition. var numbers = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 } ; var evenNumbers = numbers . Where ( n => n % 2 == 0 ) . ToList ( ) ; // Output: [2, 4, 6] C# Copy 2.  Select  (Projection) The  Select()  method projects each element of a sequence into a new form, allowing transformation of data. var employees = new List < Employee > { /* ... */ } ; var employeeNames = employees . Select ( e => e . Name ) . ToList ( ) ; // Output: List of employee names C# Copy 3.  OrderBy  (Sorting in Ascending Order) The  Or...

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...