如何构建Mono/Flux链并在Spring WebFlux中实现重试。

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

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&lt;ResponseA&gt; callA(Request1 requestA) {
	// calling service-A using webclient
}
public Flux&lt;ResponseB&gt; 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 -&gt; {

    // 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 -&gt; {

                // 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);
}

huangapple
  • 本文由 发表于 2020年10月12日 07:29:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64309989.html
匿名

发表评论

匿名网友

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

确定