您需要使用Spring的AsyncResult
类来包装您的结果,然后使用它的方法.completable()
来返回CompletableFuture
对象。
在合并Future对象时,请使用CompletableFuture.thenCompose()和CompletableFuture.thenApply()方法来合并数据,如下所示:
CompletableFuture<Integer> result = futureData1.thenCompose(fd1Value ->
futureData2.thenApply(fd2Value ->
merge(fd1Value, fd2Value)));
这是一个基本示例:
在 Spring Boot 主类上使用 @EnableAsync
注解进行注释。
@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(3000);
return new AsyncResult<Integer>(2).completable();
}
}
Bservice.java
@Service
public class Bservice {
@Async
public CompletableFuture<Integer> getData() throws InterruptedException {
Thread.sleep(2000);
return new AsyncResult<Integer>(1).completable();
}
}
创建另一个服务,用于合并其他两个服务的数据
ResultService.java
@Service
public class ResultService {
@Autowired
private Aservice aservice;
@Autowired
private Bservice bservice;
public CompletableFuture<Integer> mergeResult() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> futureData1 = aservice.getData();
CompletableFuture<Integer> futureData2 = bservice.getData();
return futureData1.thenCompose(
fd1Value -> futureData2.thenApply(fd2Value -> fd1Value + fd2Value));
}
}
创建一个用于测试的示例控制器
ResultController.java
@RestController
public class ResultController {
@Autowired
private ResultService resultService;
@GetMapping("/result")
CompletableFuture<Integer> getResult() throws InterruptedException, ExecutionException {
return resultService.mergeResult();
}
}
Thread.join
?为什么不让ResultController
直接返回另一个带有聚合的CompletableFuture
呢? - Edwin DalorzoExecotor
创建bean:@Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(3); executor.setMaxPoolSize(15); executor.setQueueCapacity(500); executor.setThreadNamePrefix("GithubLookup-"); executor.initialize(); return executor; }
。请查看此链接以获取更多信息:https://spring.io/guides/gs/async-method/ - Ajit Soman