RestTemplate 5xx服务端错误请求自动重试
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
- RestTemplateAutoConfiguration.java
@Slf4j
@Configuration
public class RestTemplateAutoConfiguration {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder, RetryTemplate retryTemplate) {
ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
final RestTemplateBuilder restTemplateBuilder = builder
.setConnectTimeout(Duration.ofSeconds(10_000L))
.setReadTimeout(Duration.ofSeconds(120_000L))
.errorHandler(errorHandler)
.additionalInterceptors(
(request, body, execution) -> retryTemplate.execute(ctx -> {
if (ctx.getRetryCount() > 0) {
log.warn("request retry attempt #{}, url=>{}", ctx.getRetryCount(), request.getURI());
}
ClientHttpResponse response = execution.execute(request, body);
if (response.getStatusCode().is5xxServerError()) {
errorHandler.handleError(response);
}
return response;
})
);
return restTemplateBuilder.build();
}
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
Map<Class<? extends Throwable>, Boolean> exceptions = new HashMap<>();
exceptions.put(HttpServerErrorException.class, true);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(5, exceptions);
retryTemplate.setRetryPolicy(retryPolicy);
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(1000);
backOffPolicy.setMaxInterval(10000);
backOffPolicy.setMultiplier(2);
retryTemplate.setBackOffPolicy(backOffPolicy);
return retryTemplate;
}