1

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.

djkelly99
  • 590
  • 4
  • 9
  • In your case, if you want to track the state, you should not use a `StatelessBackOffPolicy` like `FixedBackOffPolicy`. Maybe something like `ExponentialBackOffPolicy` will give you that control. You can subclass it and assign that to the `retryTemplate` and log stuff in your custom class. – Sunil Dabburi Dec 06 '19 at 03:03
  • Thanks, and my apologies but the FixedBackOffPolicy was a copy/paste error. I've corrected the question now to reflect this. I am using the ExponentialBackoffPolicy. Even if I was to subclass this policy however I don't see any way of accessing the internal backOff time. I would somehow have to maintain and manage my own backOff time which would nullify the benefits of using the spring library in the first place. – djkelly99 Dec 06 '19 at 10:12

1 Answers1

1

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);
    }

}
Gary Russell
  • 166,535
  • 14
  • 146
  • 179