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);
}
}
You would need a custom
BackOffPolicy
; you can get the exception type from theRetryContext
in thestart()
method.You could use a similar technique to that used in the
ExceptionClassifierRetryPolicy
which delegates to different retry policies based on the exception type.