繁体   English   中英

一旦在 Spring Boot 中收到两个响应,Call 2 External API 如何并行并执行合并

[英]How Call 2 External API parallel and perform merge once both response are received in Spring Boot

我有一个小要求,我将有一个唯一 ID。

使用此 ID,我需要对 2 个不同的系统执行 Rest GET 调用,例如系统 1 和系统 2,这将返回来自不同系统的 2 个 JSON 有效负载。

之后,一旦收到 JSON Payload,如果来自系统 1 的有效负载存在任何更改,我需要合并。

我只是想知道是否有任何可以用来完成此任务的 Spring Boot 功能,我的主要要求是

1:对系统 1 和系统 2 的 GET 请求应该并行。

2:仅在收到来自系统的响应后才执行有效载荷的合并和比较。

请建议您是否有一些我可以使用的好的参考或模板。

提前致谢。

您需要为两个 api 调用使用可完成的功能接口。 此接口内的代码将异步运行。 下面是它的示例代码。

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
    try {
        //api call1
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return "Result of the asynchronous computation";
}

});

CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
    try {
        //api call2
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return "Result of the asynchronous computation";
}

});

String result1 = future1.get();
String result2 = future2.get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM