RestTemplate 5xx服务端错误请求自动重试

发布于:2024-05-20 ⋅ 阅读:(168) ⋅ 点赞:(0)

RestTemplate 5xx服务端错误请求自动重试

  • pom.xml
		<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;
    }

网站公告

今日签到

点亮在社区的每一天
去签到