I am trying to consume RabbitMQ messages in C# using RabbitMQ.Client library and get the list of messages and add it to an array before returning the array. Following this, I was hoping to process this array and send it to a new queue. So my first approach is below:
public async Task<List<string>> ProcessMessages()
{
var factory = new ConnectionFactory { HostName = "local"};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "myqueue");
var consumer = new EventingBasicConsumer(channel);
var messages= new List<string>();
consumer.Received += async (model, ea) =>
{
var body = ea.Body.ToString();
// Do something with the to the body...
messages.Add(body);
};
channel.BasicConsume(queue: "myqueue", autoAck: acknowledge, consumer: consumer);
return messages;
}
It seems that the messages array returned is always empty. Could anyone help me out on understanding why please?
The other approach I tried is to do it within the existing Received handler:
public async Task ProcessMessages()
{
var factory = new ConnectionFactory { HostName = "local" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "myqueue");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToString();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "NewQueue1",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var newMsgBytes[] = new Byte[] // Do some processing of message and send new message to new queue
channel.BasicPublish(exchange: string.Empty,
routingKey: "NewQueue1",
basicProperties: null,
body: newMsgBytes);
};
channel.BasicConsume(queue: "myqueue", autoAck: acknowledge, consumer: consumer);
}
This also does not seem to work as the new messages is not sent to a queue. Any suggestions please? Thanks
Try reading this way (instead of
ea.Body.ToString(), useea.Body.ToArray())More details are here https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html