Issue
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.
Solution
Use a custom BackOffPolicy
that delegates to the desired BackOffPolicy
, depending on the lastThrowable
in the retryContext
.
Answered By - Gary Russell
Answer Checked By - Terry (JavaFixing Volunteer)