Search code examples
c#.net-corerabbitmqeasynetq

How to programmatically resend messages that have faulted with EasyNetQ?


I am wondering how to resend messages that have faulted with EasyNetQ, programmatically, without using HosePipe, that is to resend to their original target queue using their original sending exchange.

Is it possible, how?


Solution

  • The solution I came up with is:

    public static class AdvancedBusExtensions
    {
        public static async Task ResendErrorsAsync(this IAdvancedBus source, string errorQueueName)
        {
            var errorQueue = await source.QueueDeclareAsync(errorQueueName);
            var message = await source.GetMessageAsync(errorQueue);
            while (message != null)
            {
                var utf8Body = Encoding.UTF8.GetString(message.Body);
                var error = JsonConvert.DeserializeObject<Error>(utf8Body);
                var errorBodyBytes = Encoding.UTF8.GetBytes(error.Message);
                var exchange = await source.ExchangeDeclareAsync(error.Exchange, x =>
                {
                    // This can be adjusted to fit the exchange actual configuration 
                    x.AsDurable(true);
                    x.AsAutoDelete(false);
                    x.WithType("topic");
                });
                await source.PublishAsync(exchange, error.RoutingKey, true, error.BasicProperties, errorBodyBytes);
                message = await source.GetMessageAsync(errorQueue);
            }
        }
    }