๐ก Whatโs a Retry?
A retry means trying an operation again if it fails the first time. For example:
- Your app calls a weather API.
- It fails because of a slow connection.
- You try again after 1 second โ and it works! ๐ค๏ธ
- Retries help your app become more reliable, especially when dealing with temporary issues.
โ๏ธ Doing Retries in Spring Boot (The Simple Way)
Step 1
Spring Boot has a library called Spring Retry that makes this super easy.Letโs add it first.
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Step 2
Enable retries in your main class
@SpringBootApplication
@EnableRetry
public class RetryDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RetryDemoApplication.class, args);
}
}
Step 3
Use @Retryable, so wherever a method might fail (for example, calling an external API), you can tell Spring to retry automatically.
@Service
public class WeatherService {
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 2000))
public String callWeatherAPI() {
System.out.println("Calling weather API...");
if (Math.random() < 0.7) {
throw new RuntimeException("API failed!");
}
return "Weather is Sunny โ๏ธ";
}
@Recover
public String recover(RuntimeException e) {
return "Weather service is temporarily unavailable ๐ง๏ธ";
}
}
๐ Whatโs Happening Here
- @Retryable โ Tells Spring to retry this method up to 3 times.
- @Backoff(delay = 2000) โ Wait 2 seconds between retries.
- @Recover โ If all retries fail, this method is called instead of crashing the app.
Retries are like giving your app a second chance to succeed.
With just two annotations โ @Retryable and @Recover โ you can make your Spring Boot app much more reliable.
Top comments (0)