Suppose you have a method for which you want to retry at a specific interval if any exception occurs.
Below are the steps using Spring Retry:
Add below maven dependenciess:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
Steps for call:
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5); //Max retry #
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(1500); // Retry @ every1.5 seconds
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
// Asumption method m1 is sending String as return type
String outputStr =m1();
return outputStr;
}
});
RetryCallback should be defined with <[ReturnType Of Method],[Exception to be Retried]>.
Here in case, I have assumed the called method is returning String & retry in case of an instance of Exception is thrown.
Below are the classes need to import:
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;