英文:
Spring WebFlux : Timeout Handler invoked even when it hasn't timed out
问题
我想了解为什么在下面的代码中会调用超时处理程序。因为我已将超时配置为100秒,所以当元素在1秒后被发出时,我并不希望调用处理程序。
以下是输出的代码部分:
public static void main(String[] args) throws InterruptedException {
Mono<Integer> integerMono = Mono.just(1).delayElement(Duration.ofSeconds(1));
integerMono
.timeout(Duration.ofSeconds(100), handler())
.subscribe(integer -> System.out.println(integer));
Thread.sleep(10000);
}
private static Mono<? extends Integer> handler() {
System.out.println("handler invoked");
return Mono.just(10);
}
以下是输出:
handler invoked
1
有人可以解释一下为什么会出现这种行为,以及如何实现预期的行为吗?
英文:
I want to understand why the timeout handler is invoked in below code. Since, I had configured the timeout of 100 seconds, I wasn't expecting the handler to be invoked as the element was being emitted after 1 second.
public static void main(String[] args) throws InterruptedException {
Mono<Integer> integerMono = Mono.just(1).delayElement(Duration.ofSeconds(1));
integerMono
.timeout(Duration.ofSeconds(100),handler())
.subscribe(integer -> System.out.println(integer));
Thread.sleep(10000);
}
private static Mono<? extends Integer> handler() {
System.out.println("handler invoked");
return Mono.just(10);
}
below is the output :
handler invoked
1
can someone please explain, why it's behaving so, and how do we achieve the expected behaviour?
答案1
得分: 2
你的handler()
方法在每次调用时都会被触发。这是一个简单的Java方法,创建了一个Mono
对象。但是这个Mono
只会在超时后被订阅。
你可以像这样修改你的处理方法进行测试:
private Mono<? extends Integer> handler() {
System.out.println("Handler assembling");
return Mono.just(10)
.doOnSubscribe(subscription ->
System.out.println("Handler subscribed"));
}
关于组装和订阅的区别,可以参考这篇博客文章。
这个Stack Overflow的回答也可能会有帮助。
英文:
Your handler()
method is invoked every time you call it. It's a simple Java method that creates Mono
object. But this Mono
will be subscribed only after timeout.
You can change your handler method like this to test it:
private Mono<? extends Integer> handler() {
System.out.println("Handler assembling");
return Mono.just(10)
.doOnSubscribe(subscription ->
System.out.println("Handler subscribed"));
}
There is a blog post about assembly and subscription differences.
That SO answer could be helpful too.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论