从数据库中获得具有可完成的未来的结果

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

我正在使用Spring Boot和Spring Data Jpa,并且我具有由db中要并行运行的3个请求组成的逻辑。我想为此使用CompletableFuture。

最后,我需要根据5个数据库查询运行的结果构建响应对象。目前有3个我正在循环运行。

所以我创建了CompletableFuture

CompletableFuture<Long> totalFuture = CompletableFuture.supplyAsync(() ->  myRepository.getTotal());

CompletableFuture<Long> countFuture = CompletableFuture.supplyAsync(() ->  myRepository.getCount());

然后,我打算在将来使用.allOf。但是循环调用有问题。如何重写它以在每个请求中使用callable,我需要从请求传递值,然后按键排序到map中?

Map<String, Integer> groupcount = new HashMap<>();
    request.ids().forEach((key, value) -> count.put(key, myRepository
            .getGroupCountId(value));
java spring-boot completable-future
1个回答
0
投票

为了更透彻地解释,我发布了一个我想链接的代码段,但现在它像这样工作。

List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
Map<String, Integer> groupcount = new ConcurrentHashMap<>();
        for (var id : request.Ids().entrySet()) {
            completableFutures.add(
                CompletableFuture.runAsync(someOperation, EXECUTOR_SERVICE)
                    .thenApply(v -> runQuery(v.getValues))
                    .thenAcceptAsync(res-> groupcount .put(v.key, res));
        }
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).get();
© www.soinside.com 2019 - 2024. All rights reserved.