首页 > 解决方案 > 有没有办法为 Rest Template 提供动态超时?

问题描述

我正在使用 Spring Rest 模板和 apache 的 PoolingHttpClientConnectionManager 进行 API 调用。我正在处理的项目需要为我通过 rest 模板发出的每个 HTTP 请求设置自定义超时。为了实现这一点,我将 CompletableFuture 与单独的 ExecutorService 一起使用并调用 get(Timeout) 方法。

    try{
        CompletableFuture<BidResponse> future = CompletableFuture.supplyAsync(() -> bidderService.getBid(), executorService);
        bidResponse = future.get(bidderTimeout, TimeUnit.MILLISECONDS);
       } catch (InterruptedException | TimeoutException | ExecutionException e) {
            bidResponse = getTimeoutBidResponse();
       }

不幸的是,这种方法的问题在于,在超时的情况下,底层线程会继续工作,直到其余模板完成其调用。所以我有点从线程池中丢失了一个线程,以及从 HTTP 连接池中丢失了一个连接。有没有办法在我们收到超时异常后立即关闭 HTTP 连接,并将 HTTP 连接返回到池中?

ps 我还尝试使用带有 Mono.timeout 的 Spring Webclient。结果它实际上立即关闭了 HTTP 连接,但没有将其返回到 HTTP 池。

标签: spring-bootconnection-poolingresttemplatecompletable-futurespring-webclient

解决方案


@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) 
{
    return restTemplateBuilder
       .setConnectTimeout(...)
       .setReadTimeout(...)
       .build();
}

推荐阅读