4

I'm using spring-retry (with java 8 lambda) to retry the failed REST calls. I want to retry only for those call which returned 500 error. But I'm not able to configure retrytemplate bean for that. Currently the bean is simple as follows:

@Bean("restRetryTemplate")
public RetryTemplate retryTemplate() {

    Map<Class<? extends Throwable>, Boolean> retryableExceptions= Collections.singletonMap(HttpServerErrorException.class,
            Boolean.TRUE);
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3, retryableExceptions);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);

    return template;
}

Can anybody help me with this. Thanks in advance.

VaibS
  • 1,627
  • 1
  • 15
  • 21
  • Did you check out this SO question? https://stackoverflow.com/questions/27236216/is-it-possible-to-set-retrypolicy-in-spring-retry-based-on-httpstatus-status-cod – Mikhail Kholodkov May 13 '18 at 11:21

1 Answers1

11

So I solved my problem by creating custom RetryPolicy in following way:

RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(new InternalServerExceptionClassifierRetryPolicy());

and the implementation is as follows:

public class InternalServerExceptionClassifierRetryPolicy extends ExceptionClassifierRetryPolicy {

    public InternalServerExceptionClassifierRetryPolicy() {

        final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        simpleRetryPolicy.setMaxAttempts(3);

        this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
            @Override
            public RetryPolicy classify(Throwable classifiable) {
                if (classifiable instanceof HttpServerErrorException) {
                    // For specifically 500 and 504
                    if (((HttpServerErrorException) classifiable).getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR
                            || ((HttpServerErrorException) classifiable)
                                    .getStatusCode() == HttpStatus.GATEWAY_TIMEOUT) {
                        return simpleRetryPolicy;
                    }
                    return new NeverRetryPolicy();
                }
                return new NeverRetryPolicy();
            }
        });
    }
}

Hopefully this will help you.

Ben
  • 3,989
  • 9
  • 48
  • 84
VaibS
  • 1,627
  • 1
  • 15
  • 21