Spring WebFlux:Timeout处理程序甚至在未超时时被调用

huangapple go评论83阅读模式
英文:

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&lt;Integer&gt; integerMono = Mono.just(1).delayElement(Duration.ofSeconds(1));

    integerMono
     .timeout(Duration.ofSeconds(100),handler())
     .subscribe(integer -&gt; System.out.println(integer));

    Thread.sleep(10000);
  }

  private static Mono&lt;? extends Integer&gt; handler() {
    System.out.println(&quot;handler invoked&quot;);
    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&lt;? extends Integer&gt; handler() {
	System.out.println(&quot;Handler assembling&quot;);
	return Mono.just(10)
			.doOnSubscribe(subscription -&gt;
					System.out.println(&quot;Handler subscribed&quot;));
}

There is a blog post about assembly and subscription differences.

That SO answer could be helpful too.

huangapple
  • 本文由 发表于 2020年10月9日 15:39:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64275843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定