Вам нужно использовать класс Spring AsyncResult
, чтобы обернуть ваш результат, а затем использовать его метод .completable()
, чтобы вернуть CompletableFuture
объект.
При объединении будущего объекта используйте CompletableFuture.thenCompose () и CompletableFuture.thenApply () для объединения данных следующим образом:
CompletableFuture<Integer> result = futureData1.thenCompose(fd1Value ->
futureData2.thenApply(fd2Value ->
merge(fd1Value, fd2Value)));
Вот базовый c пример:
Annotate Spring основной класс загрузки с @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(1000 * 3); // sleep for 3 sec
return new AsyncResult<>(2).completable(); // wrap integer 2
}
}
Bservice. java
@Service
public class Bservice {
@Async
public CompletableFuture<Integer> getData() throws InterruptedException {
Thread.sleep(1000 * 2); // sleep for 2 sec
return new AsyncResult<>(1).completable(); // wrap integer 1
}
}
Создать другой сервис который объединит два других служебных данных
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();
CompletableFuture<Integer> result = futureData1.thenCompose(fd1Value ->
futureData2.thenApply(fd2Value ->
fd1Value + fd2Value)); // add future integer data
return result;
}
}
Создать образец контроллера для тестирования
ResultController. java
@RestController
public class ResultController {
@Autowired
private ResultService resultService;
@GetMapping("/result")
CompletableFuture<Integer> getResult() throws InterruptedException, ExecutionException {
return resultService.mergeResult();
}
}