Saturday, 2 May 2020

Spring Retry Mechanism

Distributed this mechanism into 3 parts and configurations are as follows-

1. Simple retry :


  • Add dependency in pom.xml 

                <dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->
 <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.6.2</version>
</dependency>


  • Add annotation in spring boot application along with @SpringBootApplication

            @EnableRetry

  • Add retry annotation on any method 
            @Retryable(value = { CustomException.class }, maxAttempts = 3, backoff = @Backoff(delay = 1000))



2. Retry and recover :

  • Add dependency in pom.xml 

                <dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->
 <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.6.2</version>
</dependency>


  • Add annotation in spring boot application along with @SpringBootApplication

            @EnableRetry

  • Add retry annotation on any method 



            @Retryable(value = { CustomException.class }, maxAttempts = 3, backoff = @Backoff(delay = 1000))
                   public String doService(String module) { }
  • Add recover annotation along with method, This method will call when all retry completed with failure. 
            @Recover
       public String getRecover(RuntimeException e) {}

3. Retry with recover and Listener:

  • Add dependency in pom.xml 

                <dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->
 <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.6.2</version>
</dependency>


  • Add annotation in spring boot application along with @SpringBootApplication

            @EnableRetry

  • Add retry annotation on any method having listener key and array of string as value



            @Retryable(listeners= {"deepRetryListener"},value = { CustomException.class }, maxAttempts = 3, backoff =                                           @Backoff(delay = 1000))
                   public String doService(String module) { }
  • Add recover annotation along with method, This method will call when all retry completed with failure. 
  •             @Recover
           public String getRecover(RuntimeException e) {}

  • Add a new class having extend RetryListenerSupport 
                    @Component
                      public class DeepRetryListener extends RetryListenerSupport {}