Spring RestTemplate: Exponential Backoff retry policy

15,177

Solution 1

Good day!

I guess, desired behavior could be achived by implementing custom Sleeper class.

Next you need to set this sleeper to BackOffPolicy as follows:

public class RetryTest {

  public static final Logger LOG = LoggerFactory.getLogger(RetryTemplate.class);

  @org.junit.Test
  public void testRT() {
    RetryTemplate retryTemplate = new RetryTemplate();
    final SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);
    retryTemplate.setRetryPolicy(retryPolicy);

    Sleeper sleeper = new Sleeper() {
      private long timeToSleep = 0;
      @Override
      public void sleep(long timeout) throws InterruptedException {
        if (timeToSleep ==0) {
          timeToSleep = timeout;
        } else {
          timeToSleep = (long) (timeToSleep * Math.E);
        }
        LOG.warn("sleeping for: {}", timeToSleep);
        Thread.sleep(timeToSleep);
      }
    };
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy().withSleeper(sleeper);
    retryTemplate.setBackOffPolicy(backOffPolicy);
    retryTemplate.execute(new RetryCallback<Void, ResourceAccessException>() {
      @Override
      public Void doWithRetry(RetryContext retryContext) throws ResourceAccessException {
        LOG.debug(">RetryCount: {}", retryContext.getRetryCount());
        new RestTemplate().getForObject("https://unreachable.host", String.class);
        return null;
      }
    });
  }
}

Also there is ExponentialBackOffPolicy by spring-retry.

Hope this would help.

Solution 2

You can use like the below code .

@Retryable(exceptionExpression="#{@exceptionChecker.shouldRetry(#root)}",
  maxAttemptsExpression = "#{@integerFiveBean}",
  backoff = @Backoff(delayExpression = "#{1}", 
    maxDelayExpression = "#{5}", multiplierExpression = "#{1.1}"))
public void service3() {
  ...
}
Share:
15,177

Related videos on Youtube

Simon
Author by

Simon

I started as a really novice android developer. Like as in I just started reading a book. But I have learnt a lot now and what an experience it has been. Lately, I have already been really interested in using Zipline for Algorithmic Trading. So I started a blog on this topic, you can find it here: https://financialzipline.wordpress.com I have also developed a fully-fledged android app: https://play.google.com/store/apps/details?id=com.bekwaai&amp;hl=en

Updated on June 04, 2022

Comments