英文:
How to make chain of Mono/Flux and implement Retry in sping-webflux
问题
public Mono<ResponseA> callA(Request1 requestA) {
// 使用 webclient 调用服务-A
}
public Flux<ResponseB> callB(Request2 requestB) {
// 使用 webclient 调用服务-B,但要创建 requestB,我需要 ResponseA。
}
英文:
I have a scenario with reactive/async call. I am using spring-boot-starter-webflux
and using webclient
to make external HTTP calls.
My scenario is I have to make a call to callA() and then check its response ResponseA. If its ResponseA is ok than exit and return ResponseA.
Otherwise create second request requestB using ResponseA and make a call to callB(). Then check its response ResponseB.
If it is ok then return ResponseA otherwise doRetry on callA().
public Mono<ResponseA> callA(Request1 requestA) {
// calling service-A using webclient
}
public Flux<ResponseB> callB(Request2 requestB) {
// calling service-B using webclient but to create requestB, I need ResponseA.
}
答案1
得分: 0
只需在`flatMap`中编写一些if语句。可能需要将其拆分为一些更好的函数名称等。无需订阅,无阻塞。
callA(createNewRequest()).flatMap(response1 -> {
// 验证响应
if(!isValidResponse(response)) {
// 如果验证失败,创建新请求并进行新调用
var request = buildRequest(response);
return callB(request).flatMap(response2 -> {
// 验证第二个响应
if(!isValidResponse(response2)) {
// 验证失败,返回第一个响应。
return Mono.just(response1)
}
// 否则递归调用
return callA(createNewRequest()); // 警告:这可能会导致无限循环
}
}
// 验证通过
return Mono.just(response);
}
英文:
you just need to do some if-statements in a flatMap
. Probably split it up into some better function names etc. No subscribing, no blocking.
callA(createNewRequest()).flatMap(response1 -> {
// Validate response
if(!isValidResponse(response)) {
// if failed validation, create new request and do a new call
var request = buildRequest(response);
return callB(request).flatMap(response2 -> {
// validate second response
if(!isValidResponse(response2)) {
// failed validation return the first response.
return Mono.just(response1)
}
// otherwise recursively call again
return callA(createNewRequest()); // Warning this can be an infinite loop
}
}
// Validation passed
return Mono.just(response);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论