目前我正在编写一种使用 WebClient 向另一个服务发送 POST 请求的方法。
private Mono<GameEntity> callApplication(GameEntity gameEntity) throws URISyntaxException {
WebClient client = WebClient.create();
for(int i=0;i<NUM_OF_RETRY;++i) {
String port = strategy.getNextInstancePort();
URI uri = new URI(String.format("http://localhost:%s/game/add", port));
try {
Mono<GameEntity> response = client.post()
.uri(uri)
.contentType(MediaType.APPLICATION_JSON)
.body(Mono.just(gameEntity), GameEntity.class)
.retrieve()
.bodyToMono(GameEntity.class)
.timeout(Duration.ofSeconds(3))
return response;
} catch (WebClientRequestException e) {
//....
} catch (Exception e) {
strategy.incrErrorCount(port);
}
}
return null;
}
我的做法是,当超时的时候,我们需要调用另外一个方法
strategy.incrErrorCount(port)
。但 Web 客户端不会抛出任何可以在 catch (Exception e)
块中捕获的异常。
超时时访问该方法有什么解决办法吗?
如果您指的是由于
而发生的超时.timeout(Duration.ofSeconds(3))
然后
timeout()
操作员还有另一个签名
public final Mono<T> timeout(Duration timeout, Mono<? extends T> fallback)
来自java文档:
切换到后备 Mono,以防在给定时间内没有物品到达 期间。如果后备 Mono 为 null,则发出 TimeoutException 信号 相反。
因此,您可以将
strategy.incrErrorCount(port)
传递到该方法中,这样该行将如下所示:
.timeout(Duration.ofSeconds(3), Mono.fromSupplier(() -> strategy.incrErrorCount(port)))