In rabbitmq, Fanout Exchange will route messages to all of the queues that are bound to it.
The fanout exchange is useful when we want to publish a common message to all the queues that are bound with particular exchange and in fanout exchange the routing key is ignored.
For example, if company has updated some guidelines and you want push those guidelines to all the branches that time you can use fanout exchange.
Generally, in rabbitmq when producer creates a message that will not directly send to queue, instead first the message will be send to exchanges, then after that a routing agent reads and sends it to the appropriate queue with help of header attributes, bindings and routing keys.
In rabbitmq, we have a different type of exchanges available those are
To know more about exchanges in rabbitmq, check this RabbitMQ Exchanges.
Following is the pictorial representation of message flow in rabbit fanout exchange.
Now, we will learn how to use Fanout Exchange to push and read messages from rabbitmq in c# or .net application with examples.
Let’s create a simple console application with Name “RequestRabbitMQ” like as shown below to publish a messages to rabbitmq queue using fanout exchange in c#.
After creating an application, now we will add “RabbitMQ.Client” nuget package in our c# application to communicate with rabbitmq server to publish or consume messages from queues in rabbitmq.
In c#, we can publish or consume messages from rabbitmq by using RabbitMQ.Client nuget package for that, right click on your application and select Manage NuGet Packages like as shown below.
Now search for RabbitMQ.Client package and install it in your application like as shown below.
Following is the another way to install RabbitMQ.Client package by using Package Manager Console like as shown below by entering following command.
Command to install - Install-Package RabbitMQ.Client -Version 5.1.0
Before we start write a code in c# to publish a messages to rabbitmq, we will create a fanout exchange, queue and will bind a queue to exchange using web admin console.
To create an exchange in rabbitmq web management portal, open http://localhost:15672/#/exchanges url and then go to Add a new exchange panel and enter a details like as shown below by selecting Type as “fanout” and click on Add exchange button to create an exchange (fanout.exchange).
After creating an exchange (fanout.exchange), next we will create 4 queues (Mumbai, Hyderabad, Bangalore and Chennai) and bind it to the same exchange (fanout.exchange) in web management portal.
To create a queue in rabbitmq web management portal, open http://localhost:15672/#/queues url and then go to Add a new queue panel and enter a details like as shown below and click on Add queue button to create a queue (Mumbai).
Similar way, add remaining three queues (Bangalore, Chennai, Hyderabad) in rabbitmq like as shown below.
After adding all the queues, next we will bind all the queues to “fanout.exchange” in rabbitmq web admin console.
To bind a queue with exchange, click on queue (Bangalore) name, then the Bindings panel will expand and enter a details like exchange name as “fanout.exchange” and click on Bind button like as shown below.
After binding a queue (Bangalore) to exchange (fanout.exchange), the binding will be like as shown below.
Same way, bind remaining queues (Chennai, Hyderabad, Mumbai) also to an exchange (fanout.exchange) in rabbitmq web admin console.
After completion of binding a queues (Bangalore, Chennai, Hyderabad, Mumbai) to an exchange (fanout.exchange), now we will publish a messages from c# application to rabbitmq queues using RabbitMQ.Client service.
To publish a messages to rabbitmq queue, add a class with name “Fanoutmessages.cs” in your application like as shown below.
Now, open Fanoutmessages.cs class file and write the code like as shown below.
using System;
using RabbitMQ.Client;
using System.Text;
namespace RequestRabbitMQ
{
public class Fanoutmessages
{
private const string UName = "guest";
private const string PWD = "guest";
private const string HName = "localhost";
public void SendMessage()
{
//Main entry point to the RabbitMQ .NET AMQP client
var connectionFactory = new ConnectionFactory()
{
UserName = UName,
Password = PWD,
HostName = HName
};
var connection = connectionFactory.CreateConnection();
var model = connection.CreateModel();
var properties = model.CreateBasicProperties();
properties.Persistent = false;
byte[] messagebuffer = Encoding.Default.GetBytes("Message is of fanout Exchange type");
model.BasicPublish("fanout.exchange", "", properties, messagebuffer);
Console.WriteLine("Message Sent From : fanout.exchange");
Console.WriteLine("Routing Key : Routing key is not required for fanout exchange");
Console.WriteLine("Message Sent");
}
}
}
If you observe above code, to establish a connection with rabbitmq server we are passing a required credentials along with HostName to ConnectionFactory() method. After that, we are publishing a message (Message is of fanout Exchange type) to queue by passing required parameters like exchange, routing key, properties and message to BasicPublish method.
Now open Program.cs class file and write a code in Main method to call Fanoutmessages.cs class to get a messages from rabbitmq.
Following is the code which we need to write in Program.cs class file Main method to publish a messages to rabbitmq server.
using System;
namespace RequestRabbitMQ
{
class Program
{
static void Main(string[] args)
{
Fanoutmessages fanoutmessages = new Fanoutmessages();
fanoutmessages.SendMessage();
Console.ReadLine();
}
}
}
When we execute above c# program, we will get the result like as shown below.
After executing above program, if we check the queues (Bangalore, Chennai, Hyderabad, Mumbai) status details in rabbitmq web management portal, the Ready column is having 1 like as shown below that means message published successfully to all the queues of fanout exchange.
After creating an application, now add “RabbitMQ.Client” nuget package reference to your application like as we did in publishing application to communicate with rabbitmq server.
After installing RabbitMQ.Client, next add a class with name “MessageReceiver.cs” in your application like as shown below to read or get a messages from queues in rabbitmq.
Now, open MessageReceiver.cs class file and write the code like as shown below.
using System;
using System.Text;
using RabbitMQ.Client;
namespace RabbitMQConsumer
{
public class MessageReceiver : DefaultBasicConsumer
{
private readonly IModel _channel;
public MessageReceiver(IModel channel)
{
_channel = channel;
}
public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body)
{
Console.WriteLine($"Consuming fanout Message");
Console.WriteLine(string.Concat("Message received from the exchange ", exchange));
Console.WriteLine(string.Concat("Consumer tag: ", consumerTag));
Console.WriteLine(string.Concat("Delivery tag: ", deliveryTag));
Console.WriteLine(string.Concat("Routing tag: ", routingKey));
Console.WriteLine(string.Concat("Message: ", Encoding.UTF8.GetString(body)));
_channel.BasicAck(deliveryTag, false);
}
}
}
If you observe above code, we created a MessageReceiver class and it’s inheriting from DefaultBasicConsumer class of RabbitMQ.Client service and we implemented a HandleBasicDeliver method by overriding it to receive a message body.
Now open Program.cs class file and write a code in Main method to call MessageReceiver.cs class to get a messages from rabbitmq.
Following is the code which we need to write in Program.cs class file Main method to receive a data from rabbitmq server.
using System;
using RabbitMQ.Client;
namespace RabbitMQConsumer
{
class Program
{
private const string UName = "guest";
private const string Pwd = "guest";
private const string HName = "localhost";
static void Main(string[] args)
{
ConnectionFactory connectionFactory = new ConnectionFactory
{
HostName = HName,
UserName = UName,
Password = Pwd,
};
var connection = connectionFactory.CreateConnection();
var channel = connection.CreateModel();
// accept only one unack-ed message at a time
// uint prefetchSize, ushort prefetchCount, bool global
channel.BasicQos(0, 1, false);
MessageReceiver messageReceiver = new MessageReceiver(channel);
channel.BasicConsume("Mumbai", false, messageReceiver);
Console.ReadLine();
}
}
}
If you observe above example, to establish a connection with rabbitmq server we are passing a required credentials along with HostName to ConnectionFactory() method. After that, we created a connection and channel by calling “CreateConnection” and “CreateModel” methods and we set a prefetchCount to 1, so that it tells RabbitMQ not to give more than one message at a time to worker.
Next, we have created an instance of MessageReceiver class and passed IModel (channel) to it, in final step we have called “BasicConsume” method and passed queue name to it “Mumbai” along with we have set autoAck to false and passed the messageReceiver instance to it.
Here, prefetchCount is used to tell RabbitMQ not to give more than one message at a time to worker. Or, in other words, don't dispatch a new message to a worker until it has processed and acknowledged the previous one. Instead, it will dispatch to the next worker that is not still busy.
When we execute our application, we will get a messages from queue (Mumbai) like as shown below.
After reading the messages from Mumbai queue, following is the status of queue in web management portal.
Same way, we can read a messages from Bangalore or Chennai or Hyderabad queue based on our requirements.
This is how we can use fanout exchange in rabbitmq to publish a messages to all the quues which are bound with an exchange.