Paul Plato
Paul Plato

Reputation: 1501

Is it possible to customize the backoff policy used by a retry template based on HttpStatus Code

I am evaluating spring-retry for a use case where we need to automatically retry certain API Calls Based on Status Code. I am able to customize the retry policy like this

@Component("httpStatusCodeRetryPolicy")
public class HttpStatusRetryPolicy extends ExceptionClassifierRetryPolicy
{
    @PostConstruct
    public void init()
    {
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        this.setExceptionClassifier( new Classifier<Throwable, RetryPolicy>()
        {
            @Override
            public RetryPolicy classify(Throwable classifiable )
            {
                if ( classifiable instanceof HttpStatusCodeException)
                {
                    var exception = (HttpStatusCodeException)classifiable;
                    if(exception.getStatusCode() == HttpStatus.REQUEST_TIMEOUT){
                       retryPolicy.setMaxAttempts(3);
                    }
                    else if (exception.getStatusCode() == HttpStatus.valueOf(429) ||
                    exception.getStatusCode() == HttpStatus.valueOf(502) ||
                    exception.getStatusCode() == HttpStatus.valueOf(503) ||
                    exception.getStatusCode() == HttpStatus.valueOf(504)) {
                        retryPolicy.setMaxAttempts(4);
                    }
                    return retryPolicy;
                }
                return new NeverRetryPolicy();
            }
        });
    }
}

However, I want to also customize the backoff policy based on these status codes. I want to use a FixedBackOff policy for some response status code and an ExponentialBackOffPolicy for the rest. I looked around and have not found any pointers.

Upvotes: 0

Views: 378

Answers (1)

Gary Russell
Gary Russell

Reputation: 174769

Use a custom BackOffPolicy that delegates to the desired BackOffPolicy, depending on the lastThrowable in the retryContext.

Upvotes: 2

Related Questions