带有多线程的Spring boot异步

问题描述 投票:0回答:2

我有一个spring boot微服务,我们将其称为多个服务(假设服务A和服务B)。我试图根据某些条件在多个线程上异步调用这两个服务,一旦处理完成,我想合并来自服务A和ServiceB的响应。

我知道我们可以使用@Async异步运行一个进程,并使用ExecutorService启动一个服务的多个线程。

但是我不确定如何将所有东西放在一起。因此,在这里寻找任何建议吗?

              @Async
              Service A(thread1,thread2) \
MicroService /                             (Merge from Response of ServiceA and ServiceB)
             \ @Async
              Service B(thread1,thread2) /

我知道这在理论上基本上已经在上面进行了解释,但是我尝试在多个网站上进行跟踪/浏览,但是大多数文章都解释了有关Aync或多线程的问题,但是不确定如何在多个线程中等待并运行Async中的两个进程并在执行之后继续执行这两个服务呼叫已完成!

任何建议或潜在客户均表示赞赏! TIA:)

java spring multithreading spring-boot asynchronous
2个回答
0
投票

您可以查看Java的CompletableFuture。 ComplitableFuture允许合并多个异步任务(也都是CompletableFuture),并等待所有CompletableFutures的结果。我不确定它是否完全适合您的情况,但这可能会有所帮助。https://www.baeldung.com/java-completablefuture#Multiple


0
投票

您需要使用spring的AsyncResult类包装结果,然后使用其方法.completable()返回CompletableFuture对象。

合并将来的对象时,使用以下代码等待所有将来的任务完成。

CompletableFuture.allOf(futureData1,futureData2, ...).join();

然后使用futureData.get()方法获取数据,然后合并结果。

这是一个基本示例:

使用@EnableAsync注释对Spring启动主类进行注释

@SpringBootApplication
@EnableAsync
public class StackOverflowApplication {

    public static void main(String[] args) {
        SpringApplication.run(StackOverflowApplication.class, args);
    }

}

创建将返回CompletableFuture的示例服务

Aservice.java

@Service
public class Aservice {

    @Async
    public CompletableFuture<Integer> getData() throws InterruptedException {
        Thread.sleep(1000 * 3);
        return new AsyncResult<>(2).completable();
    }
}

Bservice.java

@Service
public class Bservice {

    @Async
    public CompletableFuture<Integer> getData() throws InterruptedException {
        Thread.sleep(1000 * 2);
        return new AsyncResult<>(1).completable();
    }
}

创建另一个将合并其他两个服务数据的服务

ResultService.java

@Service
public class ResultService {

    @Autowired
    private Aservice aservice;
    @Autowired
    private Bservice bservice;

    public int mergeResult() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> futureData1 = aservice.getData();
        CompletableFuture<Integer> futureData2 = bservice.getData();
        CompletableFuture.allOf(futureData1,futureData2).join(); // wait till all are done
        return futureData1.get()+futureData2.get();

    }
}

创建用于测试的样本控制器

ResultController.java

@RestController
public class ResultController {

    @Autowired
    private ResultService resultService;

    @GetMapping("/result")
    int getResult() throws InterruptedException, ExecutionException {
        return resultService.mergeResult();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.