RECEIVING MESSAGES FROM A DIRECT 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 DIRECT QUEUE IN RABBITMQ.

The code

This sets up an event driven reception of the messages. The system will push the messages to the consumer app using events.

var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (sender, eventArgs) =>
{
    var bodyArray = eventArgs.Body.ToArray();

    var message = 
        (MqMessage?)ObjectSerialize
           .DeSerialize(bodyArray, typeof(MqMessage));

    Console.WriteLine(message.Message);
};

_channel.BasicConsume(QueueName, true, consumer);
Console.ReadLine();

The code explained

var consumer = new EventingBasicConsumer(_channel);

This creates the object that will do the event handling for you.

We have to tell it what channel to listen to.

consumer.Received += (sender, eventArgs) => 
    {
        /* Add business logic here */
    };

It is only we, the developers, that know what to do with the messages. So, we have to do the work and write the code. This is the place  where we do that.

The parameter eventArgs will contain the data we receive.

var bodyArray = eventArgs.Body.ToArray();
var message = 
    (MqMessage?)ObjectSerialize
       .DeSerialize(bodyArray, typeof(MqMessage));

Here, we start with transforming the message from the bit array that RabbitMQ uses to send messages with, into our app specific object.

After that it’s up to us to process the object the way we need. In this case, since it’s just an example, we only need proof of concept, so we just print the message string from it.

_channel.BasicConsume(QueueName, true, consumer);

This line starts the event handling. It will run until the app stops…

Console.ReadLine();

… so, we make sure it doesn’t by just adding this line.

Hey, it’s just an example, you will do it properly in your code!

— Cheers!

Like it? Share it!

Leave a Reply

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