【问题标题】:Spring Boot Webclient - wait end response of multi callSpring Boot Webclient - 等待多呼叫的结束响应
【发布时间】:2019-11-04 22:27:10
【问题描述】:

我多次调用休息端点并使用 jpa 将响应保存在数据库中。收到所有响应后,我必须调用数据库中的存储过程。

我正在尝试使用 Web 客户端执行此请求,但我不知道如何等待/检查所有请求是否已完成。

这是我用来调用端点的代码:

private Mono<DSGetDataResponse> GetData(DSGetDataRequest dataRequest){
try {
   return
    weblicent.post()
    .uri("GetData")              
        .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON_UTF8)
        .syncBody(dataRequest)
        .retrieve()
        .bodyToMono(DSGetDataResponse.class);
} catch (Exception e) {
log.info("Sono in catch (Exception");
e.printStackTrace();
return null;
        }
    }

这是我用来调用上述方法的代码

Items_to_request().forEach( x -> {
 String token = tokenResponse.getTokenValue();
DSGetDataRequest dataRequest = new DSGetDataRequest(token, this.Richista_DS(x), null);
try{
    this.GetData(dataRequest).subscribe(dataResponse ->   this.handlerGetDataResponse(dataResponse));
}
catch (Exception e)
{log.info("Sono in catch (Exception");
e.printStackTrace();
}
});

在 handlerGetDataResponse 上,我只将响应保存在数据库中。

如何等待所有请求完成后调用数据库中的存储过程?

我知道我将无阻塞调用与阻塞调用混合在一起

您对如何解决问题有什么建议吗?

谢谢 米尔科

【问题讨论】:

    标签: rest spring-boot asynchronous jpa-2.0 spring-webflux


    【解决方案1】:

    我已经使用 Flux 重写了你的代码

    Flux.fromIterable(Items_to_request())
    .flatMap( x -> {
        String token = tokenResponse.getTokenValue();
        DSGetDataRequest dataRequest = new DSGetDataRequest(token, this.Richista_DS(x), null);
        return this.GetData(dataRequest));
    })
    .onErrorResume(<add your logic>)
    .collectList()
    .subscribe(List<Data> data -> {< do what you want here})
    

    您必须使用 onErrorResume 或 onErrorContinue 或类似运算符正确处理错误,否则通量将终止。检查here

    此代码将触发所有请求并将响应收集到一个列表中,然后订阅它。

    【讨论】:

    • 我认为 flatMap lambda 内部的 subscribe 调用是不需要的
    • 是的。我只是复制了问题中的任何内容而忘记删除它。现在编辑我的回复。
    猜你喜欢
    • 2020-02-14
    • 2022-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2018-04-27
    相关资源
    最近更新 更多