Java循环直至webclient返回Mono的条件

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

Java Loop until condition for webclient returning Mono

问题

我有一段Java WebClient的代码,其中我将响应转换为Mono<R>。我想在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();
    })

但是没有用。

英文:

I have a java webclient code , the response of which I convert to Mono<R>. I want to iterate on the api call until the Mono response matches certain condition. Of course I do not want to iterate till infinity. I want to iterate after every 5 seconds until 30 seconds. So far I have tried this

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

client.get()
                .uri(&quot;https://someUri&quot;)
                .retrieve()

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

<!-- end snippet -->

But no use.

答案1

得分: 3

你可以这样使用过滤器、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>
英文:

You can use a filter, repeatWhenEmpty and Repeat like so

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

The Repeat class is part of the reactor-extra library

&lt;dependency&gt;
    &lt;groupId&gt;io.projectreactor.addons&lt;/groupId&gt;
    &lt;artifactId&gt;reactor-extra&lt;/artifactId&gt;
&lt;/dependency&gt;

huangapple
  • 本文由 发表于 2020年5月5日 18:41:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/61611207.html
匿名

发表评论

匿名网友

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

确定