I am creating a user that runs in an infinite loop to read messages from a queue. I am looking for advice / example code on how to restore abd continue in my infinite loop, even if there are network failures. The consumer must remain on as it will be installed as a WindowsService.
1) Can someone explain how to use these settings correctly? What is the difference between the two?
NetworkRecoveryInterval
AutomaticRecoveryEnabled
RequestedHeartbeat
2) Please see my current sample code for the consumer. I am using .Net RabbitMQ Client v3.5.6.
How will the above settings for "recovery" be performed? for example, will user.Queue.Dequeue block until it is restored? It doesn't seem right so ...
Do I need to enter the code for this manually? for example, will user.Queue.Dequeue throw an exception for which I have to detect and manually recreate my connection, channel and consumer? Or just a consumer, since AutomaticRecovery will restore the channel for me?
Does this mean that I should move the consumer creation inside the while loop? how about creating a channel? and making a connection?
3) Assuming I have to execute some of this recovery code manually, are there any event callbacks (and how do I register for them) to let me know that there are network problems?
Thanks!
public void StartConsumer(string queue)
{
using (IModel channel = this.Connection.CreateModel())
{
var consumer = new QueueingBasicConsumer(channel);
const bool noAck = false;
channel.BasicConsume(queue, noAck, consumer);
while (channel.IsOpen &&
Connection.IsOpen &&
consumer.IsRunning)
{
try
{
BasicDeliverEventArgs item;
if (consumer.Queue.Dequeue(Timeout, out item))
{
string message = System.Text.Encoding.UTF8.GetString(item.Body);
DoSomethingMethod(message);
channel.BasicAck(item.DeliveryTag, false);
}
}
catch (EndOfStreamException ex)
{
}
catch (Exception ex)
{
}
}
}
}
public IConnection Connection
{
get
{
if (_connection == null)
{
_connection = CreateConnection();
}
return _connection;
}
}
private IConnection CreateConnection()
{
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "RabbitMqHostName",
UserName = "RabbitMqUserName",
Password = "RabbitMqPassword",
};
factory.AutomaticRecoveryEnabled = true;
factory.NetworkRecoveryInterval = TimeSpan.FromSeconds(5);
factory.RequestedHeartbeat = 5;
IConnection connection = factory.CreateConnection();
return connection;
}
source
share