'Retryrequest() of httpClient method not invoked during Rest API call

The Rest API responds with 429 error code and the retry has to trigger 3 times .But the control isn't reaching the retryrequestethod of HttpRequestretryHandler class. Any specific reason for this ? Pseudo code below:-

@Override protected CloseableHttpClient newClient() {
 return HttpClients.custom()
   .disableAutomaticRetries().setServiceUnavailabilityRetryStrategy(retryCount,retryIntervalinMillis).setConnectionManager().setKeepAliveStrategy()
   .build();
}

@Bean
public RestTemplate resttemplate(){
   return new ResttemplateBuilder().requestFactory(this::clientHttpRequestFactory).build();
}

    private static Class HttpServiceUnavailabilityStrategy implements ServiceUnavailabilityStrategy{
@Override
public boolean retryrequest(HttpResponse resp,int executionCount,HttpContext){
return executionCount < = maxRetryCount && resp.getStatusLine().getStatusCode() == HttpStatus.TOO_MANY_REQUESTS.value();

    }


Solution 1:[1]

setServiceUnavailabilityRetryStrategy needs ServiceUnavailableRetryStrategy instance. I am not seeing you have set it correctly. You might need to do following inside newClient :

return HttpClients.custom()
   .disableAutomaticRetries().setServiceUnavailabilityRetryStrategy(new ServiceUnavailableRetryStrategy() {                 
                    @Override
                    public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                        return executionCount < = maxRetryCount && resp.getStatusLine().getStatusCode() == HttpStatus.TOO_MANY_REQUESTS.value();;
                    }
                    @Override
                    public long getRetryInterval() {
                        return 0; //you can set intervanl based on your need
                    }                   
                }).setConnectionManager().setKeepAliveStrategy()
   .build();

Moreover, by this way, you don't really need to define HttpServiceUnavailabilityStrategy class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashish Patil