Skip to main content

Spring boot retry tutorial

Spring Retry API

Spring provides spring-retry API for running business logic with retry options and recovery method or operations. In this tutorial we will learn the usage of all these with example. We are using Spring boot application here for our example code.

Maven dependencies

To use spring retry we need below dependencies.

spring-retry

This API provides many annotations which we can use in a declarative manner to implement the same.
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <version>1.2.5.RELEASE</version>
        </dependency>

spring-boot-starter-aop

Spring AOP is also required for retry implementation.
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

Retry implementation

To implement retry with our business logic we need to follow steps mentioned in this section.
  1. Enable retry

  2. To enable retry we need to add below annotation on Spring boot main class.
    @EnableRetry
    
  3. Service interface with Retry annotations

    In service interface we have two methods for business logic which we will execute with retry option and then two recovery methods, one for each business logic. Retry annotation defines the maxAttempts for number of times to retry the execution and backoff attribute defines the delay in milliseconds during each attempt. Recovery methods are mapped with the best matching of method signature for business method. If it is not able to match any of recovery method for a given retry business method then it will throws an exception for no recovery methods found.
    Method "sayHello" with recovery method. If this method is not able to respond in three attempts then it will call the recovery method with default message.
        @Retryable(value=Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
        public String sayHello(String name)throws Exception;
    
        @Recover
        public String fallbackMessage(String name);
    
    Method "sum" with recovery method. If this method is not able to provide sum in three attempts then it will call the recovery method which will return -1.
        @Retryable(value=Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
        public int sum(int a, int b)throws Exception;
    
        @Recover
        public int fallbackSum();
    
  4. Service class implementation

    This class will provide the implementation for the above interface. Below is the complete code for this class.
    import org.springframework.retry.annotation.Recover;
    import org.springframework.stereotype.Service;
    
    @Service
    public class HelloServiceImpl implements HelloService {
        @Override
        public String sayHello(String name) throws Exception {
            System.out.println("Executing sayHello");
            if("ERROR".equals(name))
                throw new Exception("Throwing exception for retry...");
            return "Hello "+name+"!";
        }
        @Override
        public String fallbackMessage(String name) {
            return name+": Couldn't say hello. Try next time.";
        }
    
        @Override
        public int sum(int a, int b) throws Exception {
            System.out.println("Executing sum");
            if(a+b==0)
                throw new Exception("Throwing exception for retry...");
            return a+b;
        }
        @Override
        public int fallbackSum(){
            return -1;
        }
    }
    
  5. Spring boot main class implementation

    Main class is a Spring boot main class which contains main method. Here we will call service methods for both scenario when it is able to respond without error and when it has to retry three times with recovery option. We are using Spring application events to execute this code once Spring boot application is up and running. Below is the complete code for this class.
    @EnableRetry
    @SpringBootApplication
    public class RetryDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(RetryDemoApplication.class, args);
        }
    
        @Autowired
        HelloService helloService;
    
        @EventListener(ApplicationReadyEvent.class)
        public void test()throws Exception{
            System.out.println(helloService.sayHello("ERROR"));
            System.out.println(helloService.sayHello("Black pearl"));
            System.out.println("-----------------------------------------------------");
            System.out.println("Sum: "+helloService.sum(0, 0));
            System.out.println("Sum: "+helloService.sum(10, 20));
    
        }
    }
    

Executing application

If we run this application then you will see that it is executing the "test" method from main class once application is started. Below is the output after the code execution and here, you can notice that it tries the code to execute three time and then executed recovery method due to all failed attempts. Then it has executed one success scenario where it is able to execute logic in first attempt without any error.
2020-02-16 11:35:23.989  INFO 8519 --- [           main] com.ttj.retrydemo.RetryDemoApplication   : Started RetryDemoApplication in 16.511 seconds (JVM running for 16.886)
Executing sayHello
Executing sayHello
Executing sayHello
ERROR: Couldn't say hello. Try next time.
Executing sayHello
Hello Black pearl!
-----------------------------------------------------
Executing sum
Executing sum
Executing sum
Sum: -1
Executing sum
Sum: 30

Source code

You can download the complete source code from below Github location.
https://github.com/thetechnojournals/spring-tutorials/tree/master/retry-demo


Comments

Post a Comment

Popular Posts

Setting up kerberos in Mac OS X

Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database. Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application. Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below. brew install krb5 Once installation is complete, we need to set the below export commands in user's profile which will make the kerberos utility commands and compiler available to execute from anywhere. Open user's bash profile: vi ~/.bash_profile Add below lines: export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS=&

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check. havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false. matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment. name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "property.name" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"} prefix - It can be use when you want to apply some prefix to

Multiple data source with Spring boot, batch and cloud task

Here we will see how we can configure different datasource for application and batch. By default, Spring batch stores the job details and execution details in database. If separate data source is not configured for spring batch then it will use the available data source in your application if configured and create batch related tables there. Which may be the unwanted burden on application database and we would like to configure separate database for spring batch. To overcome this situation we will configure the different datasource for spring batch using in-memory database, since we don't want to store batch job details permanently. Other thing is the configuration of  spring cloud task in case of multiple datasource and it must point to the same data source which is pointed by spring batch. In below sections, we will se how to configure application, batch and cloud task related data sources. Application Data Source Define the data source in application properties or yml con

Entity to DTO conversion in Java using Jackson

It's very common to have the DTO class for a given entity in any application. When persisting data, we use entity objects and when we need to provide the data to end user/application we use DTO class. Due to this we may need to have similar properties on DTO class as we have in our Entity class and to share the data we populate DTO objects using entity objects. To do this we may need to call getter on entity and then setter on DTO for the same data which increases number of code line. Also if number of DTOs are high then we need to write lot of code to just get and set the values or vice-versa. To overcome this problem we are going to use Jackson API and will see how to do it with minimal code only. Maven dependency <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency> Entity class Below is