I'm currently playing around with Rabbit-Mq, and am trying to implement a "dead-letter" queue, a queue for failed messages. I've been reading the rabbit documentation: https://www.rabbitmq.com/dlx.html.
and have come up with this example:
internal class Program
{
private const string WorkerExchange = "work.exchange";
private const string RetryExchange = "retry.exchange";
public const string WorkerQueue = "work.queue";
private const string RetryQueue = "retry.queue";
static void Main(string[] args)
{
var factory = new ConnectionFactory { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(WorkerExchange, "direct");
channel.QueueDeclare
(
WorkerQueue, true, false, false,
new Dictionary<string, object>
{
{"x-dead-letter-exchange", RetryExchange},
// I have tried with and without this next key
{"x-dead-letter-routing-key", RetryQueue}
}
);
channel.QueueBind(WorkerQueue, WorkerExchange, string.Empty, null);
channel.ExchangeDeclare(RetryExchange, "direct");
channel.QueueDeclare
(
RetryQueue, true, false, false,
new Dictionary<string, object> {
{ "x-dead-letter-exchange", WorkerExchange },
{ "x-message-ttl", 30000 },
}
);
channel.QueueBind(RetryQueue, RetryExchange, string.Empty, null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
Thread.Sleep(1000);
Console.WriteLine("Rejected message");
// also tried channel.BasicNack(ea.DeliveryTag, false, false);
channel.BasicReject(ea.DeliveryTag, false);
};
channel.BasicConsume(WorkerQueue, false, consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
Image of queue when publishing to worker queue:
I feel as though I'm missing some small details but can't seem to find what they are.
Thanks in advance