In a project, there might be a use case where you need to re-invoke a failed operation or call a method again on failure.
Spring Retry provides declarative retry support for Spring applications.
In this blog, we will configure and use Spring Retry logic using Spring Application.
Link for other versions of spring-retry.
Please Note: You will also need dependent jars for Spring Retry.
1. Enable Spring Retry in SpringBoot Application
2. Use retry logic on a method using annotation.
@Retryable: To add retry functionality to methods, @Retryable can be used.
@Recover: The @Recover annotation is used to define a recovery method when a @Retryable method fails with a specified exception.
Points to Note
- Retry will be called only when ArithmeticException is thrown from method block in above example.
- Method will retry max 4 times [maxAttempts = 4] with a deay of 500ms [backoff = @Backoff(500))]
- @Retryable without any attribute will try 3 times with a delay of 1 sec if the method fails with an exception.
- @Recover is called when the @Retryable method fails ie after trying maxAttempts times.
- In @Recover the return type must match the @Retryable method.
- The arguments for the recovery method can optionally include the exception that was thrown, and also optionally the arguments passed to the original retryable method (or a partial list of them as long as none are omitted).
- For a random backoff between 100 and 500 milliseconds. @Retryable(maxAttempts=12, backoff=@Backoff(delay=100, maxDelay=500))
1. If the return type is not matched you get below mentioned error. For example, if you’re recover block code is
2. If no of arguments exceed in recover method you will get below mentioned error. For example, if you’re recover block code is
Download Sample Project used for this Blog.
- To Run: Inside project root dir run: mvn spring-boot:run
- Hit http://localhost:8080/testRetry?id=2 in a browser.