spring-boot - 有没有办法为 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 池。
解决方案
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder)
{
return restTemplateBuilder
.setConnectTimeout(...)
.setReadTimeout(...)
.build();
}
推荐阅读
- reactjs - 从 API 获取数据后如何更改状态?
- node.js - 传递到快递时的日期更改?
- javascript - React Router Dom 不渲染组件但更改 URL
- react-native - 当退格和 TextInput 的长度 = 0 时如何获取事件
- python - 张量流性能混乱
- docker - Docker 在 Windows WSL 上的 Ubuntu 中运行
- ios - 如何从 Snapchat SDK 获取 Bitmoji 以显示在我的 UIView 中
- css - Bootstrap 4 卡列 - 每列 X 个卡
- python - 注册账号后 Django 无法识别用户 *AnonymousUser*
- javascript - 如何从 PHP Echo 传回输入值?