Whenever communication happens between software applications ,
there is a chance of network failure or timeout .
In such case , the failed application should retry the communication to make it success.
Setup
Dependency for Spring-Retry,
<dependency>
<groupid>org.springframework.retry</groupid>
<artifactid>spring-retry</artifactid>
<version>1.1.2.RELEASE</version>
</dependency>
Spring Retry uses AOP, so make sure you use Spring AOP ,
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-aop</artifactid>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.8</version>
</dependency>
If you are using Spring Boot, you can use spring-boot-starter-aop instead,
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-aop</artifactid>
</dependency>
To enable Spring Retry in your application youd need to annotate main class with @EnableRetry annotation.
@EnableRetry
@SpringBootApplication
public class MainApplicationForSpringRetry {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Retry handling using annotation:
Annotate the appropriate methods with @Retryable annotation
@Service
public class RertyService {
@Retryable
public void retryMethod() {
//method to be retried
}
}
Methods annotated with @Retryable can be called like any other methods.
Whenever retryable method fails with an exception, Spring will automatically retry for three times.
By default Spring uses a 1 second delay between method calls.
Please note that the calling thread blocks during retry handling.
The retry can be customized . For example:
@Service
public class MyService {
@Retryable(value = {Exception1.class, Exception2.class}, maxAttempts = 5)
public void retryMethodWithException() {
// your code
}
@Recover
public void recoverMethodForException1(Exception1 exception) {
// to recover from Exception1
}
}
Here Spring apply retry handling only if a Exception of type Exception1 or Exception2 is thrown.
Other exceptions will not cause a retry.
maxAttempts = 5 means Spring will retry the method up to 5 times if it fails.
With @Recover we define a separate recovery method for Exception1.
This allows us to run special recovery code when a retryable method fails with Exception1.
No comments:
Post a Comment