【发布时间】:2020-01-25 15:13:28
【问题描述】:
我正在一个项目反应堆研讨会上工作,并坚持以下任务:
/**
* TODO 5
* <p>
* For each item call received in colors flux call the {@link #simulateRemoteCall} operation.
* Timeout in case the {@link #simulateRemoteCall} does not return within 400 ms, but retry twice
* If still no response then provide "default" as a return value
*/
我无法解决的问题是 Flux 实际上从未抛出 TimeOutException!我可以在控制台日志中观察到这一点:
16:05:09.759 [main] INFO Part04HandlingErrors - Received red delaying for 300
16:05:09.781 [main] INFO Part04HandlingErrors - Received black delaying for 500
16:05:09.782 [main] INFO Part04HandlingErrors - Received tan delaying for 300
我试图调整语句的顺序,尽管它似乎并没有改变行为。注意:此外,我尝试了 timeout() 的重载变体,它接受一个默认值,如果没有发出任何元素,则应该返回该值。
public Flux<String> timeOutWithRetry(Flux<String> colors) {
return colors
.timeout(Duration.ofMillis(400))
//.timeout(Duration.ofMillis(400), Mono.just("default"))
.retry(2)
.flatMap(this::simulateRemoteCall)
.onErrorReturn(TimeoutException.class, "default");
}
有人可以解释为什么没有发生超时吗?我怀疑该机制在某种程度上没有“绑定”到 flatMap 调用的方法。
为了完整性:辅助方法:
public Mono<String> simulateRemoteCall(String input) {
int delay = input.length() * 100;
return Mono.just(input)
.doOnNext(s -> log.info("Received {} delaying for {} ", s, delay))
.map(i -> "processed " + i)
.delayElement(Duration.of(delay, ChronoUnit.MILLIS));
}
更完整,这是我为验证功能而进行的测试:
@Test
public void timeOutWithRetry() {
Flux<String> colors = Flux.just("red", "black", "tan");
Flux<String> results = workshop.timeOutWithRetry(colors);
StepVerifier.create(results).expectNext("processed red", "default", "processed tan").verifyComplete();
}
【问题讨论】:
标签: java project-reactor