SENDING MESSAGES WITH A FANOUT QUEUE IN RABBITMQ

Setting up a direct queue

If you haven’t done so already, have a look at how you set up the direct queue here:
SETTING UP A FANOUT QUEUE IN RABBITMQ.

The code

_channel.BasicPublish(
    exchange: ”MyExchangeName”,
    routingKey: ””,
    basicProperties: null,
    body: ObjectSerialize.Serialize(message));

public static byte[]? Serialize(object? obj) =>
    null != obj
         ? Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(obj))
         : null;

The code explained

_channel.BasicPublish(
    exchange: ”MyExchangeName”,
    routingKey: ””,
    basicProperties: null,
    body: ObjectSerialize.Serialize(message));

Sending data is easy. Just call the BasicPublish() method on the channel.

To send a message with Fanout queues, we use the name of the Exchange to connect the sender and receivers. The message will be sent to all queues that are connected to the exchange. The receivers add their queues to the list when they connect to the Exchange.

Since the message will be sent to all queues, the Routing Key is not used in a Fanout scenario, and we leave it as a blank string.

RECEIVING MESSAGES FROM A FANOUT QUEUE

public static byte[]? Serialize(object? obj) =>
    null != obj
         ? Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(obj))
         : null;

The data we want to send is stored in objects. Now, RabbitMQ can’t handle every conceivable class in the world, it’s just not practical. Or even possible.

RabbitMQ is a generic system, and it as such, needs a generic way of sending data. So it’s up to us to turn our objects into that uniform data type. That’s why we convert it to a byte array.

— Cheers!

Like it? Share it!

Leave a Reply

Your email address will not be published. Required fields are marked *