Mono / Flux:如何挂起线程并等待事件或超时

时间:2019-08-08 13:29:31

标签: java kotlin project-reactor

我想请教如何解决Mono / Flux暂停和通过延迟或超时重新激活的问题。

任务是:应用程序将接收HTTP请求并应提供响应。

使用异步套接字接收请求时,应发送消息。而且我们需要等待特定的答案,但不要超过30秒。

因此,我需要暂停线程,直到将调用某些Runnable,或者其他选项是每隔0.2秒查询一些变量,如果将其设置为相关值,则继续执行该过程。

能给我一些建议吗?

谢谢

2 个答案:

答案 0 :(得分:3)

我认为您需要使用Mono / Flux中的超时方法来设置该行为。示例:

yourMonoOrFlux.timeout(Duration.ofSeconds(30))
              .onErrorResume(yourFallbackMethod)
              ... //some other chained operations

当出现问题时,还可以使用onErrorResume方法设置后备方法。

但是,如果您需要在这30秒内真正阻塞线程,则应该使用阻塞方法而不是超时。示例:

yourMonoOrFlux.block(Duration.ofSeconds(30))
              ... //other chained operations 

参考官方reactor documentation

答案 1 :(得分:0)

最后我找到了解决方法。

也许不是最优雅,但可以使用递归

此代码查询变量状态以获得肯定的响应,但超时时间不超过10秒。

val delayDuration = Duration.ofMillis(200)
val maximumAttempts = 50

fun createDelayedMono(counter : Int) : Mono<BigInteger> {

    val mono = Mono.delay(delayDuration).flatMap {
        it ->

        if (counter < maximumAttempts && reactorHelper.isEventCompleted(rrn)) {
            reactorHelper.removeEvent(rrn)
            return@flatMap Mono.just(BigInteger.ZERO)
        } else {
            return@flatMap createDelayedMono(counter + 1)
        }

    }

    return mono
}