victorio
victorio

Reputation: 6646

Different retry attempts for different exceptions in Spring @Retryable

In my SpringBoot app I have a Client, which can send a POST request. And during POST it can have several exceptions.

I want to have a retry logic in case of 2 different exceptions. But in a way that the max-retry-attempts should take effect for each exception, and not together. Hard to explain, but an example:

The max-retry-attempts is configured for 3. If I get exception1 type, than retry, I have 2 retry left. Try again and get again exception1, then retry and now I have 1 retry left. Try again and now I get exception2, then try and now I have again 2 retry left, because the previous retries were for the exception1 but not for exception2. So exception2 retry has just started.

Is it possible? I tried with this, but this does not starts over the retry-attempts for different exception, if exception1 occured and then exception2 occured, then I had 1 retry left:

@Retryable(maxAttempts = 3, value = {Exception1.class, Exception2.class}, backoff = @Backoff(delay = 3000, multiplier = 2))

Upvotes: 6

Views: 9866

Answers (2)

Farid Jafri
Farid Jafri

Reputation: 356

I don't think something exists for the @Retryable annotation. If you choose to use RetryTemplate implementation, you can use the following to have different retry attempts for different exceptions and set it into the RetryTemplate object:

final SimpleRetryPolicy simpleRetryPolicyTenTimes = new SimpleRetryPolicy();
simpleRetryPolicyTenTimes.setMaxAttempts(10);
final SimpleRetryPolicy simpleRetryPolicyTwoTimes = new SimpleRetryPolicy();
simpleRetryPolicyTwoTimes.setMaxAttempts(2);
final Map<Class<? extends Throwable>, RetryPolicy> policyMap = new HashMap<>();
policyMap.put(RetryException.class, simpleRetryPolicyTenTimes);
policyMap.put(HardFailException.class, simpleRetryPolicyTwoTimes);
final ExceptionClassifierRetryPolicy retryPolicy = new ExceptionClassifierRetryPolicy();
retryPolicy.setPolicyMap(policyMap);
return retryPolicy;

You can find the example here: https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.retry.policy.ExceptionClassifierRetryPolicy

Upvotes: 2

Gary Russell
Gary Russell

Reputation: 174554

You would have to create a custom retry policy; and configure it into a RetryTemplate and RetryOperationsInterceptor; use the interceptor property on the annotation to reference the interceptor.

Upvotes: 1

Related Questions