Get the current backoff value when using Spring RetryTemplate

470 views Asked by At

So I've been experimenting with Spring's Retry Template. Everything is working as expected. One thing I would like however is the ability to extract or log the current backoff time that's being used. I had a look through the docs/searched everywhere but I can't find any easy way of getting this.

    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();

        ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();

        exponentialBackOffPolicy.setMaxInterval(10000); // 10 secs
        exponentialBackOffPolicy.setMultiplier(2);    // double the backoff
        retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(2);
        retryTemplate.setRetryPolicy(retryPolicy);

        return retryTemplate;
    }

And I'm using it like this...

retryTemplate.execute(arg0 -> {
    myService.templateRetryService();
    return null;
});

The RetryCallback only provides the RetryConext but this doesn't contain what I need.

Any ideas would be welcome. Thanks.

1

There are 1 answers

1
Gary Russell On BEST ANSWER

You can set a custom Sleeper on the ExponentialBackOffPolicy to log the time.

/**
 * Public setter for the {@link Sleeper} strategy.
 * @param sleeper the sleeper to set defaults to {@link ThreadWaitSleeper}.
 */
public void setSleeper(Sleeper sleeper) {
    this.sleeper = sleeper;
}

The default sleeper is this:

@SuppressWarnings("serial")
public class ThreadWaitSleeper implements Sleeper {

    @Override
    public void sleep(long backOffPeriod) throws InterruptedException {
        Thread.sleep(backOffPeriod);
    }

}