英文:
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("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();
})
<!-- 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("https://someUri")
.retrieve()
.bodyToMono(Response.class)
.filter(response -> condition)
.repeatWhenEmpty(Repeat.onlyIf(r -> true)
.fixedBackoff(Duration.ofSeconds(5))
.timeout(Duration.ofSeconds(30)))
The Repeat class is part of the reactor-extra library
<dependency>
<groupId>io.projectreactor.addons</groupId>
<artifactId>reactor-extra</artifactId>
</dependency>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论