Reputation: 23
I need to know the total messages in RabbitMQ from .NET client. I know the best solution is using API HTTP but I doesn't work properly.
I use confirmation of published messages, but I don't know why it doesn't work.
I use this code in order to publish a message in RabbitMQ:
private void message(string text)
{
var factory = new ConnectionFactory() { HostName = hostName, UserName = user, Password = password };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
try
{
channel.ExchangeDeclare(exchangeNameProducer, "direct", true);
channel.QueueDeclare(queueNameProducer, true, false, false, null);
channel.ConfirmSelect();
channel.QueueBind(queueNameProducer, exchangeNameProducer, "");
var body = Encoding.UTF8.GetBytes(text);
channel.BasicPublish(exchangeNameProducer, "", null, body);
channel.WaitForConfirmsOrDie();
log("After WaitForConfirm ,messageCount = " + this.getMessagesCount() + " ; message = " + text);
}
catch (Exception e)
{
log(e.Message);
}
}
}
"getMessagesCount" function asks to HTTP API to know total message count. Notice I use WaitForConfirmsOrDie and ConfirmSelect functions in order to wait until the message is published.
In my example, the consumer takes 30 seconds processing the message. However, the log always prints 0 messages remaining, but If I debug the code, the log prints 1 message remaining. If I use this code (waiting 1 second after publishing the message):
channel.BasicPublish(exchangeNameProducer, "", null, body);
channel.WaitForConfirmsOrDie();
Thread.Sleep(1000);
log("After WaitForConfirm ,messageCount = " + this.getMessagesCount() + " ; message = " + text);
then it works properly and the log writes "1 message left"
I think RabbitMQ lasts a few seconds to update message count from HTTP API, or it doesn't wait in WaitForConfirmsOrDie function.
Could you help me please?
Thank you in advance.
Upvotes: 1
Views: 5896
Reputation: 2313
Take a look at the statistics interval in the management plugin: https://www.rabbitmq.com/management.html#statistics-interval
By default the DB is updated every 5 seconds, but you can configure that. Keep in mind that performance will be affected if you reduce that value, since more writes will be performed by the management DB
Upvotes: 1