Mannu
Mannu

Reputation: 259

Get queueName in Message listner of RabbitMq

I am creating multiple consumers in the loop by which I am able to listen to multiple queues. The issue in this approach is I am able to get the events from the different queues but all the queues are using the same consumer so it is hard to recognize for which queue this event happens. It will be good if I will get the queue name under the consumer section.

          consumer.Received += async (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                };

Upvotes: 2

Views: 2936

Answers (3)

developer_009
developer_009

Reputation: 367

There is no queue field on the message headers or fields, based on my re-search of message object. The only fields related to queue name are from dead-lettered messages, which save in the headers object of properties the x-first-death-queue.

Upvotes: 1

Mohsen
Mohsen

Reputation: 21

A solution is using "consumerTag" in channel.BasicConsume

channel.BasicConsume(..., consumerTag: "YourQueueName");

And then you can retrieve the queue name in message listner:

consumer.Received += async (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                var queueName = ea.ConsumerTag;
            };

Warning: In the case that ConsumerTag is important to your system, do not use this solution.

Upvotes: 2

AminSojoudi
AminSojoudi

Reputation: 2016

The ea variable has some interesting fields, have you check that?

ea.Exchange shows this message has published from which exchange.

ea.RoutingKey shows the route info of the message. probably have the queue name in it.

Also, you can put your headers in the message when your are defining them.

IBasicProperties props = channel.CreateBasicProperties();
props.Headers.Add("queueName",  "myQueue1");
channel.BasicPublish(exchangeName,
                   routingKey, props,
                   messageBodyBytes);

and in the consumer function you can read them :

consumer.Received += async (model, ea) =>
                {
                    var name = ea.BasicProperties.Headers["queueName"];
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                };

Upvotes: 3

Related Questions