I've trouble setting up a RestTemplate to retry remote calls. Does anyone know how to configure the RestTemplate to retry calls after getting 503 response status code?
Yes it is possible, you can try out custom retry policy.
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 503
if (((HttpServerErrorException) classifiable).getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE) {
return simpleRetryPolicy;
}
return new NeverRetryPolicy();
}
return new NeverRetryPolicy();
}
});
}}
Ans the simply call it as below:
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new InternalServerExceptionClassifierRetryPolicy())
Retry within the catch block
try {
responseEntity = restTemplate.exchange(endpoint, HttpMethod.POST, entity, MyResponse.class);
} catch (HttpClientErrorException hcee) {
//There is an error in request, if known, improve and retry
} catch (HttpServerErrorException hsee) {
recvdStatusCode = hsee.getStatusCode();
// Handle it within a switch case, if there is an option to retry.
}
This may be another approach, I have never tried this myself-
@Bean
public RetryTemplate retryTemplate() {
int maxAttempt = Integer.parseInt(env.getProperty("maxAttempt"));
int retryTimeInterval = Integer.parseInt(env.getProperty("retryTimeInterval"));
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempt);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(retryTimeInterval); // 1.5 seconds
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
//Here is the invocation -
retryTemplate.execute(context -> {
System.out.println("inside retry method");
ResponseEntity<?> requestData = RestTemplateProvider.getInstance().postAsNewRequest(bundle, ServiceResponse.class, serivceURL,
CommonUtils.getHeader("APP_Name"));
_LOGGER.info("Response ..."+ requestData);
throw new IllegalStateException("Something went wrong");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.