java - 在 Spring Boot 中收到两个响应后如何并行调用 2 个外部 API 并执行合并

标签 java spring multithreading rest spring-boot

我有一个小要求,我需要一个唯一的 ID。

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

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

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

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

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

请建议您是否有一些好的引用或模板可供我使用。

提前致谢。

最佳答案

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

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();

关于java - 在 Spring Boot 中收到两个响应后如何并行调用 2 个外部 API 并执行合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59390895/

相关文章:

java - 使用多线程重绘paintComponent

java - Android N textAppearence 与 Android M 不一样

java:变量初始化

java - 全局 EditText 变量

java - 如何在多个不同的对象上调用相同的刻度方法?

java - Spring 启动 2 : Get html output in controller

java - Spring Hibernate 数据库查询不起作用

java - 如何从域对象创建 JSON View ?

c# - 如何处理重复执行?

python 多处理struct.error