Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive single message from the queue in RabbitMQ using C#

Tags:

c#

rabbitmq

I would like to know how I can receive only one message at a time this is basic code for that

var factory = new ConnectionFactory() { HostName = "localhost" };
var connection = factory.CreateConnection()
var channel = connection.CreateModel()
channel.QueueDeclare("hello", false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("hello", true, consumer);

BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Response.Write(message + " Received.");
like image 883
Parag Bhayani Avatar asked Dec 03 '22 18:12

Parag Bhayani


1 Answers

If you want wait for 1 message, then keep using channel.BasicConsume, but leave consumer method after single message.

If you just get 1 message (if at least 1 exists in queue) then channel.BasicGet

var data = channel.BasicGet(queueName, true);

P.S.:

There are nice example on CloudAMQP with .NET: Getting started page.

like image 133
pinepain Avatar answered Feb 16 '23 00:02

pinepain