Spring Retry
December 22, 2022
Background
Spring retry is an easy way to add retry to your Spring application.
Spring Boot Implementation
Assuming this is a Spring Boot application,
- Add
spring-retry
andspring-boot-starter-aop
as dependencies. - Add
@EnableRetry
annotation to any @Configuration class. Adding it to the main spring boot class is fine as well. - Add
@Retryable
to any method in you code that you want to be retried on failure.value
orinclude
: List of exceptions to retry on.exclude
: List of exceptions to not retry on.maxAttempts
: Number of retry attemptsbackoff
: Backoff retry properties (time to wait between retries).- When using spring retry 1.3+ you can pass a
recover
param that takes the name of the recover function. Last I checked, Spring retry javadocs past 1.2.2 are not online so need to check maven and download the javadocs for latest version.
- Add
@Recover
to a function that defines the fallback behavior.- This is invoked when all retries failed. You could for example, log that all retries failed and return a error response entity.
Example
public class SpringRetryScratch {public static void main(String[] args) {System.out.println("Spring retry code showcase - note this will not run unless you bootstrap a spring or spring boot application");executeTask();}@Retryable(include = {RuntimeException.class}, maxAttempts = 3, backoff = @Backoff(delay = 2000L), recover = "handleTaskFailed")private static void executeTask(){throw new RuntimeException("failed");//System.out.println("Invoked operation");}@Recoverprivate static void handleTaskFailed(){System.out.println("executeTask exhausted all retries. Sending email...");}}
More Reading:
- Only official documentation (readme): https://github.com/spring-projects/spring-retry
- Choosing recover method: https://github.com/spring-projects/spring-retry/issues/188