Gun
Gun

Reputation: 521

c# Rabbit MQ Unacked messages

I have an issue when trying to send ACK to remove messages from Rabbit queue.

Version of Rabbit MQ : 3.6.15. Version of RabbitClient 5.0.1

Here is my code:

var conn = Factory.CreateConnection();
var channel = conn.CreateModel();


//inside loop
var data = Get(conn, channel);

if (data == null)
    return true;

if (data.MessageCount == 0)
    return true;

var rabbitShortAd = JsonConvert.DeserializeObject<ShortAdRabbit>(Encoding.UTF8.GetString(Decompress(data.Body)));

//Process rabbitShortAd, save it in DB 
//And if no error, send ack

SendAck(data, conn, channel);
return false;
//end loop


public static BasicGetResult Get(IConnection conn, IModel channel)
{
     if (conn == null || !conn.IsOpen)
        conn = Factory.CreateConnection();

    if (channel == null || !channel.IsOpen)
        channel = conn.CreateModel();

    var queueName = "descriptions";
    channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false);
    return channel.BasicGet(queueName, false);
}

private static void SendAck(BasicGetResult data)
{
    if (conn == null || !conn.IsOpen)
        conn = Factory.CreateConnection();

    if (channel == null || !channel.IsOpen)
        channel = conn.CreateModel();

    channel.BasicAck(data.DeliveryTag, false);
}

The first message processed is removed from the queue and then all others messages are stacking in the unacked column. My admin system just told me he updated the Rabbit MQ version to 3.6.15 and now I can't ACK my messages. Is there something wrong in the code ?

Upvotes: 1

Views: 1677

Answers (1)

Gun
Gun

Reputation: 521

Found out the wait to make it work.

I have to instantiate the connection & the model inside the loop and then close each connection / model inside, too.

//inside the loop
var conn = Factory.CreateConnection();
var channel = conn.CreateModel();

try
{
   var data = Get(conn, channel);

   //Process

   channel.BasicAck(data.DeliveryTag, false);
}
catch(Exception e)
{
   //handle e
}
finally
{
   conn?.Close();
   channel?.Close();
}
//end of loop

Upvotes: 1

Related Questions