SENDING MESSAGES WITH A HEADER QUEUE IN RABBITMQ

Setting up a header queue

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

The code

public void SendMessage(MqMessage message)
{
    var properties = _channel.CreateBasicProperties();
    properties.Headers = 
        new Dictionary<string, object>
        {
            { "stock", "update" },
            { "department", "homeelectronics" },
        };

    _channel
       .BasicPublish(
            "HeaderExchange",
            routingKey: "",
            basicProperties: properties,
            body: ObjectSerialize.Serialize(message));
}

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

The code explained

var properties = _channel.CreateBasicProperties();
properties.Headers = 
    new Dictionary<string, object>
    {
        { "stock", "update" },
        { "department", "homeelectronics" },
    };

Headers are set up via the Headers dictionary in the properties object. Just create a new dictionary and add the key-value pairs. You can add as many pairs as you need.

_channel
   .BasicPublish(
        "HeaderExchange",
        routingKey: "",
        basicProperties: properties,
        body: ObjectSerialize.Serialize(message));

The message is sent to the Exchange. RabbitMQ will then distribute the message to the receivers using the headers to filter who gets what.

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 *