I am using Retry Template which should retries 5 times on DataAccessResourceFailureException and for every other, No retry.
private static RetryTemplate setupRetryTemplate() { RetryTemplate template = new RetryTemplate();
// Set up backoff policy
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(300L);
template.setBackOffPolicy(fixedBackOffPolicy);
// Set up retry policy based on exception type
ExceptionClassifierRetryPolicy retryPolicy = new ExceptionClassifierRetryPolicy();
retryPolicy.setExceptionClassifier(exception -> {
// Retry only on specific exception type
if (exception instanceof DataAccessResourceFailureException) {
SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(5);
return simpleRetryPolicy;
} else {
return new NeverRetryPolicy(); // Do not retry for other exceptions
}
});
template.setRetryPolicy(retryPolicy);
return template;
}
Caller of method looks like below
public UserDetails loadUserByUsername(String username, Map<String, Object> attributes, String accountPickedClientId) throws UsernameNotFoundException {
return retryTemplate.execute((RetryCallback<UserDetails, RuntimeException>) context -> {
try { ...
} catch (DataAccessResourceFailureException ex) {
log.error("Exception DataAccessResourceFailureException : {}", ex.getMessage(), ex);
throw new DataAccessResourceFailureException("Mongo db connection time out");
} catch (Exception ex) {
log.error(USER_NOT_FOUND, ex);
throw new UsernameNotFoundException(USER_NOT_FOUND, ex);
}
}
It's going into an infinite loop of retries.
You are creating a new policy for each exception so it starts over each time. You need to define the policy once and return the same instance for the required exception type.