How to change the spring retry template fixed back off policy based on the exception

2k views Asked by At

I am using Spring Retry Template for retrying.

This is my method for retry, here my retry interval should be based on the Exception. For example if DataException thrown, retry should happen for 1000(1 sec) time interval or if MQException thrown, retry should happen for 5000(5 sec) time interval.

How to change the FixedBackOffPolicy instance based on the exception.

Main flow:

private void retryTest(){
                retryTemplate.execute(context -> {
                    log.info("Processing request...");
                    retryTest1();
                    return true; 
                },
                context -> {
                    log.info("Recovering request...");
                    return true;
                });

    }  

private void retryTest1(){
    throw new DataException("Data exception"); 
     //throw new MQException("MQ Message exception"); 
}

Retry Template Initialization:

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

        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(1000L);
        retryTemplate.setBackOffPolicy(new CustomBackOffPolicy());  // Custom backoff policy 

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

        
        return retryTemplate;
    }


public class CustomBackOffPolicy implements BackOffPolicy {

    @Autowired
    RetryTemplate retryTemplate;


    @Override
    public BackOffContext start(RetryContext retryContext) {
          RetryPolicy retryPolicy = (RetryPolicy) retryContext;

          return null;
    }

    @Override
    public void backOff(BackOffContext backOffContext) throws BackOffInterruptedException {
        try {
            Thread.sleep(1000l);
        } catch (InterruptedException var2) {
            throw new BackOffInterruptedException("Thread interrupted while sleeping", var2);
        }
    }
1

There are 1 answers

2
Gary Russell On BEST ANSWER

You would need a custom BackOffPolicy; you can get the exception type from the RetryContext in the start() method.

You could use a similar technique to that used in the ExceptionClassifierRetryPolicy which delegates to different retry policies based on the exception type.