有没有办法为Rest Template提供动态超时?

时间:2020-05-19 17:38:51

标签: spring-boot connection-pooling resttemplate completable-future spring-webclient

我正在使用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连接返回到池中?

p.s。我还尝试将Spring Webclient与Mono.timeout结合使用。事实证明,它实际上会立即关闭HTTP连接,但不会将其返回到HTTP池。

1 个答案:

答案 0 :(得分:0)

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