Search code examples
springspring-bootrabbitmqspring-cloudspring-cloud-stream

How to configure Spring Cloud Stream publisher retries?


I am using the RabbitMQ binder.

Spring Cloud Stream lets developers retry when exceptions happen as consuming messages.

Producers can fail when RabbitMQ connectivity has been lost. How can we configure SCS so that it retries when any error occurs as producing messages? Or is there a way to apply the circuit breaker there?

Thanks


Solution

  • You can use standard spring boot properties (retry.enabled etc) - scroll down to rabbitmq - to configure retry on the producer side. The binder will wire a retry template into the outbound adapter's RabbitTemplate.

    spring.rabbitmq.template.retry.enabled=false # Whether publishing retries are enabled.
    spring.rabbitmq.template.retry.initial-interval=1000ms # Duration between the first and second attempt to deliver a message.
    spring.rabbitmq.template.retry.max-attempts=3 # Maximum number of attempts to deliver a message.
    spring.rabbitmq.template.retry.max-interval=10000ms # Maximum duration between attempts.
    spring.rabbitmq.template.retry.multiplier=1 # Multiplier to apply to the previous retry interval.
    

    This is the code in the binder...

            if (rabbitProperties != null && rabbitProperties.getTemplate().getRetry().isEnabled()) {
                Retry retry = rabbitProperties.getTemplate().getRetry();
                RetryPolicy retryPolicy = new SimpleRetryPolicy(retry.getMaxAttempts());
                ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy();
                backOff.setInitialInterval(retry.getInitialInterval().toMillis());
                backOff.setMultiplier(retry.getMultiplier());
                backOff.setMaxInterval(retry.getMaxInterval().toMillis());
                RetryTemplate retryTemplate = new RetryTemplate();
                retryTemplate.setRetryPolicy(retryPolicy);
                retryTemplate.setBackOffPolicy(backOff);
                rabbitTemplate.setRetryTemplate(retryTemplate);
            }