1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.