Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for RabbitMQ: Using It with Microservices
Daniel Azevedo
Daniel Azevedo

Posted on

     

RabbitMQ: Using It with Microservices

Hi devs,

RabbitMQ is one of the most popularmessage brokers, enabling communication between services in a distributed system. It supports various messaging patterns, such aswork queues,publish/subscribe, andRPC. In this post, I’ll demonstrate how to set up RabbitMQ and use it to enable communication between three microservices:Order Service,Inventory Service, andNotification Service.


Why RabbitMQ?

RabbitMQ allows microservices to:

  1. Decouple communication: Services don't need to know about each other.
  2. Increase reliability: Messages are persisted until delivered.
  3. Improve scalability: Multiple consumers can process messages concurrently.
  4. Support multiple protocols: AMQP, STOMP, MQTT, etc.

Architecture Overview

In this example:

  1. Order Service publishes anOrderPlaced message to a RabbitMQ exchange.
  2. Inventory Service subscribes to the exchange to update stock.
  3. Notification Service subscribes to the exchange to send order confirmation notifications.

Prerequisites

  1. Install RabbitMQ:

    • Using Docker:
     docker run-d--name rabbitmq-p 5672:5672-p 15672:15672 rabbitmq:management
  • Access the RabbitMQ management UI athttp://localhost:15672 (default username/password:guest/guest).
  1. Install theRabbitMQ.Client package in your .NET projects:
   dotnet add package RabbitMQ.Client
Enter fullscreen modeExit fullscreen mode

Step-by-Step Implementation

Step 1: Define a Shared Order Model

publicclassOrder{publicintId{get;set;}publicstringProductName{get;set;}publicintQuantity{get;set;}publicdecimalTotalPrice{get;set;}}
Enter fullscreen modeExit fullscreen mode

This model will represent the order data shared between services.


Step 2: Create the Order Service (Producer)

TheOrder Service publishes messages to the RabbitMQ exchange.

usingRabbitMQ.Client;usingSystem.Text;usingSystem.Text.Json;publicclassOrderService{privatereadonlyIModel_channel;publicOrderService(){varfactory=newConnectionFactory(){HostName="localhost"};varconnection=factory.CreateConnection();_channel=connection.CreateModel();// Declare an exchange and a queue_channel.ExchangeDeclare(exchange:"orders_exchange",type:ExchangeType.Fanout);}publicvoidPlaceOrder(Orderorder){varmessage=JsonSerializer.Serialize(order);varbody=Encoding.UTF8.GetBytes(message);_channel.BasicPublish(exchange:"orders_exchange",routingKey:"",basicProperties:null,body:body);Console.WriteLine($"Order placed:{order.ProductName}");}}// UsagevarorderService=newOrderService();varorder=newOrder{Id=1,ProductName="Laptop",Quantity=1,TotalPrice=1500.00m};orderService.PlaceOrder(order);
Enter fullscreen modeExit fullscreen mode

Here, theOrder Service publishes anOrderPlaced event to theorders_exchange.


Step 3: Create the Inventory Service (Consumer)

TheInventory Service listens to theorders_exchange and updates stock.

usingRabbitMQ.Client;usingRabbitMQ.Client.Events;usingSystem.Text;usingSystem.Text.Json;publicclassInventoryService{publicvoidStart(){varfactory=newConnectionFactory(){HostName="localhost"};varconnection=factory.CreateConnection();varchannel=connection.CreateModel();// Declare the exchange and queuechannel.ExchangeDeclare(exchange:"orders_exchange",type:ExchangeType.Fanout);varqueueName=channel.QueueDeclare().QueueName;channel.QueueBind(queue:queueName,exchange:"orders_exchange",routingKey:"");varconsumer=newEventingBasicConsumer(channel);consumer.Received+=(model,ea)=>{varbody=ea.Body.ToArray();varmessage=Encoding.UTF8.GetString(body);varorder=JsonSerializer.Deserialize<Order>(message);Console.WriteLine($"Inventory updated for Product:{order.ProductName}, Quantity:{order.Quantity}");};channel.BasicConsume(queue:queueName,autoAck:true,consumer:consumer);Console.WriteLine("Inventory Service is running...");}}// UsagevarinventoryService=newInventoryService();inventoryService.Start();
Enter fullscreen modeExit fullscreen mode

Step 4: Create the Notification Service (Consumer)

TheNotification Service listens to theorders_exchange and sends notifications.

usingRabbitMQ.Client;usingRabbitMQ.Client.Events;usingSystem.Text;usingSystem.Text.Json;publicclassNotificationService{publicvoidStart(){varfactory=newConnectionFactory(){HostName="localhost"};varconnection=factory.CreateConnection();varchannel=connection.CreateModel();// Declare the exchange and queuechannel.ExchangeDeclare(exchange:"orders_exchange",type:ExchangeType.Fanout);varqueueName=channel.QueueDeclare().QueueName;channel.QueueBind(queue:queueName,exchange:"orders_exchange",routingKey:"");varconsumer=newEventingBasicConsumer(channel);consumer.Received+=(model,ea)=>{varbody=ea.Body.ToArray();varmessage=Encoding.UTF8.GetString(body);varorder=JsonSerializer.Deserialize<Order>(message);Console.WriteLine($"Notification sent for Order ID:{order.Id}, Product:{order.ProductName}");};channel.BasicConsume(queue:queueName,autoAck:true,consumer:consumer);Console.WriteLine("Notification Service is running...");}}// UsagevarnotificationService=newNotificationService();notificationService.Start();
Enter fullscreen modeExit fullscreen mode

How It All Works

  1. Order Service publishes anOrderPlaced event to the RabbitMQorders_exchange.
  2. RabbitMQ routes the message to all bound queues.
  3. Inventory Service andNotification Service consume the message and process it independently.

Testing the System

  1. Run theInventory Service andNotification Service.
  2. Place an order using theOrder Service.
  3. Observe the logs for the inventory update and notification.

Benefits of Using RabbitMQ in Microservices

  1. Decoupled Communication: Producers and consumers don’t need direct knowledge of each other.
  2. Scalable: Add more consumers to process messages faster.
  3. Reliable Delivery: Messages are persisted and retried if delivery fails.
  4. Flexible Messaging Patterns: Work queues, publish/subscribe, RPC, etc.

Conclusion

RabbitMQ is a powerful message broker that simplifies communication in microservices. By using theFanout Exchange pattern, we ensured that multiple services could respond to the same event independently.

Keep coding!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

C# developer passionate about clean code and design patterns. Sharing insights on software architecture, coding best practices, and tech tips. Join me on this journey to better code!
  • Location
    Portugal
  • Joined

More fromDaniel Azevedo

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp