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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With