Skip to content

Ferdinand Agyei-Yeboah

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,

  1. Add spring-retry and spring-boot-starter-aop as dependencies.
  2. Add @EnableRetry annotation to any @Configuration class. Adding it to the main spring boot class is fine as well.
  3. Add @Retryable to any method in you code that you want to be retried on failure.
    • value or include: List of exceptions to retry on.
    • exclude: List of exceptions to not retry on.
    • maxAttempts: Number of retry attempts
    • backoff: 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.
  4. 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");
}
@Recover
private static void handleTaskFailed(){
System.out.println("executeTask exhausted all retries. Sending email...");
}
}

More Reading:


Software Engineering Tutorials & Best Practices