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

Why HashMap key should be immutable in java

HashMap is used to store the data in key, value pair where key is unique and value can be store or retrieve using the key. Any class can be a candidate for the map key if it follows below rules. 1. Overrides hashcode() and equals() method.   Map stores the data using hashcode() and equals() method from key. To store a value against a given key, map first calls key's hashcode() and then uses it to calculate the index position in backed array by applying some hashing function. For each index position it has a bucket which is a LinkedList and changed to Node from java 8. Then it will iterate through all the element and will check the equality with key by calling it's equals() method if a match is found, it will update the value with the new value otherwise it will add the new entry with given key and value. In the same way it check for the existing key when get() is called. If it finds a match for given key in the bucket with given hashcode(), it will return the value other

jaxb2-maven-plugin to generate java code from XSD schema

In this tutorial I will show how to generate the Java source code from XSD schema. I will use jaxb2-maven-plugin to generate the code using XSD file which will be declared in pom.xml to make it part of build, so when maven build is executed it will generate the java code using XSD. Class generation can be controlled in plugin configuration. Maven changes (pom.xml) Include below plugin in your pom.xml. Here we have done some configuration under configuration section as given below. schemaDirectory : This is the directory where I keep my schema (XSD file). outputDirectory : This is the java source location where I want to generate the Java files. If it is not given then by default it will be generate inside target folder. clearOutputDir : If this property is true then it will generate the classes on each build otherwise it will generate only if output directory is empty. <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</art