【问题标题】:Java Loop until condition for webclient returning MonoJava循环直到webclient返回Mono的条件
【发布时间】:2020-08-19 23:59:24
【问题描述】:

我有一个 java webclient 代码,我将其响应转换为 Mono。我想迭代 api 调用,直到 Mono 响应匹配特定条件。当然,我不想迭代到无穷大。我想每 5 秒迭代一次,直到 30 秒。到目前为止,我已经尝试过这个

client.get()
                .uri("https://someUri")
                .retrieve()

                .bodyToMono(Response.class)
                .delayElement(Duration.ofSeconds(5))
                .retryBackoff(5, Duration.ofSeconds(5))
                .delayUntil(r -> {
                    System.out.print("Looping"); 
                    if(condition) {
                        System.out.print(r.getStatus());
                        return Mono.just(r);
                    }
                    return Mono.empty();
                })

但是没有用。

【问题讨论】:

    标签: java reactive-programming spring-webflux spring-webclient


    【解决方案1】:

    您可以像这样使用过滤器,repeatWhenEmpty 和 Repeat

    client.get()
        .uri("https://someUri")
        .retrieve()
        .bodyToMono(Response.class)
        .filter(response -> condition)
        .repeatWhenEmpty(Repeat.onlyIf(r -> true)
            .fixedBackoff(Duration.ofSeconds(5))
            .timeout(Duration.ofSeconds(30)))
    

    Repeat 类是 reactor-extra 库的一部分

    <dependency>
        <groupId>io.projectreactor.addons</groupId>
        <artifactId>reactor-extra</artifactId>
    </dependency>
    

    【讨论】:

    • 感谢您的回答。但它返回通量。我想要单声道
    • @BrijeshPrasad 它返回一个Mono repeatWhenEmpty 的方法签名是public final Mono&lt;T&gt; repeatWhenEmpty
    • 抱歉,我只使用了repeat 而不是repeatWhenEmpty
    猜你喜欢
    • 2013-12-09
    • 2023-03-24
    • 2015-12-13
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多