To configure different retry attempts for different exceptions using Resilience4j in your Spring Boot application while using the same fallback method, follow these steps:
✅ Step 1: Update YAML Configuration
Define two separate retry instances in your application.yml for each exception type with different retry counts:
resilience4j.retry:
instances:
retryResourceAccess:
maxAttempts: 4
retryExceptions:
- org.springframework.web.client.ResourceAccessException
retryHttpServerError:
maxAttempts: 2
retryExceptions:
- org.springframework.web.client.HttpServerErrorException
Each instance is uniquely named and configured to retry only on specific exceptions.
✅ Step 2: Modify Your Method to Allow Exceptions to Propagate
Your current method catches HttpServerErrorException, which prevents Resilience4j from detecting the exception and triggering retries.
Update your method like this:
public Response myFunction(Request req) {
ResponseEntity<Response> res = restTemplate.exchange(url, HttpMethod.POST, req, Response.class);
return res.getBody();
}
This ensures exceptions like HttpServerErrorException and ResourceAccessException are not caught locally, so Resilience4j can detect and retry them.
✅ Step 3: Apply Multiple Retry Configurations Using @Retries
Use the @Retries annotation (from resilience4j-spring-boot2) to apply both retry configurations to the same method:
@Retries({
@Retry(name = "retryResourceAccess", fallbackMethod = "retryFunction"),
@Retry(name = "retryHttpServerError", fallbackMethod = "retryFunction")
})
public Response myFunction(Request req);
This tells Spring to apply both retry policies. Each will only apply to its respective exception type.
✅ Step 4: Define the Shared Fallback Method
Your fallback method must accept the original method's parameters and a Throwable:
public Response retryFunction(Request req, Throwable t) {
// Log or handle the exception as needed
return new Response(); // Return default/fallback response
}
This single fallback method will be used for both retry configurations.
🔍 Summary
| Requirement | Solution |
|---|
Retry ResourceAccessException 4 times | Defined retryResourceAccess with maxAttempts: 4 |
Retry HttpServerErrorException 2 times | Defined retryHttpServerError with maxAttempts: 2 |
| Use same fallback method | Fallback retryFunction(Request, Throwable) |
| Exceptions must trigger retry | Removed local try-catch block to let them propagate |
| Multiple retry rules applied | Used @Retries with two @Retry annotations |
⚠️ Important Notes
- Ensure
spring-boot-starter-aop is on the classpath.
- Make sure the method annotated with
@Retries is called externally (not from within the same class) to ensure AOP proxies work.
- Always test both exception scenarios to verify correct retry behavior and fallback invocation.
By following this structure, you can customize retry behavior per exception and still reuse a single fallback method, keeping your code clean and modular.