我不确定我是否走对了路,但目前我卡住了。 我想要实现的是,我想根据它的父类别获取项目列表。
ParentCategory --< Category --< Item
并且对 CompletionStage 还不是很熟悉。
所以这里我有 2 个查询。第一个查询是获取 ParentCategory 的列表。然后我将遍历该列表以获取每个 ParentCategory 的项目列表
ParentCategoryDao {
findParentCategoriesByShop(int shopId);
}
ItemDao {
//joined query of item and child category
findItemByChildCategory(final int parentCategoryId)
}
在 Controller 中:
public CompletionStage<List<ProcessClass>> retrieveItems(final int shopId) {
parentCategoryDao.findParentCategoriesByShop(shopId).thenApplyAsync(parentCategoryStream ->{
ParentCategoryJson parentCategoryJson = new ParentCategoryJson();
for(ParentCategory parentCategory : parentCategoryStream.collect(Collectors.toList())) {
processClassJson.setProcessClassId(parentCategory.getId());
processClassJson.setProcessClassName(processClass.getProcessClass());
itemDao.findItemByChildCategory(parentCategory.getId()).thenApplyAsync(itemStream ->{
// Do operations on forming a list of items
}, ec.current());
//then maybe after is something like
processClassJson.setItemList(itemList);
}
},ec.current())
}
顺便说一下,我正在使用 Play Framework。 非常感谢任何帮助。
最佳答案
很惊讶地看到您没有在 thenApplyAsync block 中返回任何内容。此外,非阻塞函数应该只从 thenCompose 调用以避免嵌套的 CompletionStage。无论如何,下面是应该可以解决您的问题的代码。
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
....
public static CompletionStage<List<Object>> retrieveItems(final int shopId) {
return parentCategoryDao
.findParentCategoriesByShop(shopId)
.thenComposeAsync(
stream ->
resultsOfAllFutures(
stream
.map(
parentCategory ->
itemDao
.findItemByChildCategory(parentCategory.getId())
.thenApplyAsync(
itemStream -> {
// Do operations on forming a list of items
return null;
}))
.collect(Collectors.toList())));
}
public static <T> CompletableFuture<List<T>> resultsOfAllFutures(
List<CompletionStage<T>> completionStages) {
return CompletableFuture.completedFuture(null)
.thenApply(
__ ->
completionStages
.stream()
.map(future -> future.toCompletableFuture().join())
.collect(Collectors.toList()));
}
关于Java - 使用多个完成阶段来形成一个响应 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48514512/