gpt4 book ai didi

java - 循环中的 CompletableFuture : How to collect all responses and handle errors

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:44 24 4
gpt4 key购买 nike

我正在尝试为循环中的 PUT 请求调用 rest api。每个调用都是一个 CompletableFuture。每个 api 调用都会返回一个 RoomTypes.RoomType

类型的对象
  • 我想收集响应(包括成功的和错误的响应)在不同的列表中。我该如何实现?我确定我不能使用 allOf 因为它不会得到所有结果(如果有的话)一个调用更新失败。

  • 如何记录每次调用的错误/异常?


public void sendRequestsAsync(Map<Integer, List> map1) {
List<CompletableFuture<Void>> completableFutures = new ArrayList<>(); //List to hold all the completable futures
List<RoomTypes.RoomType> responses = new ArrayList<>(); //List for responses
ExecutorService yourOwnExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

for (Map.Entry<Integer, List> entry :map1.entrySet()) {
CompletableFuture requestCompletableFuture = CompletableFuture
.supplyAsync(
() ->
//API call which returns object of type RoomTypes.RoomType
updateService.updateRoom(51,33,759,entry.getKey(),
new RoomTypes.RoomType(entry.getKey(),map2.get(entry.getKey()),
entry.getValue())),
yourOwnExecutor
)//Supply the task you wanna run, in your case http request
.thenApply(responses::add);

completableFutures.add(requestCompletableFuture);
}

最佳答案

您可以简单地使用 allOf()获得一个在所有初始 future 完成时完成的 future (异常(exception)或不),然后使用 Collectors.partitioningBy() 在成功和失败之间拆分它们:

List<CompletableFuture<RoomTypes.RoomType>> completableFutures = new ArrayList<>(); //List to hold all the completable futures
ExecutorService yourOwnExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

for (Map.Entry<Integer, List> entry : map1.entrySet()) {
CompletableFuture<RoomTypes.RoomType> requestCompletableFuture = CompletableFuture
.supplyAsync(
() ->
//API call which returns object of type RoomTypes.RoomType
updateService.updateRoom(51, 33, 759, entry.getKey(),
new RoomTypes.RoomType(entry.getKey(), map2.get(entry.getKey()),
entry.getValue())),
yourOwnExecutor
);

completableFutures.add(requestCompletableFuture);
}

CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]))
// avoid throwing an exception in the join() call
.exceptionally(ex -> null)
.join();
Map<Boolean, List<CompletableFuture<RoomTypes.RoomType>>> result =
completableFutures.stream()
.collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally)));

生成的 map 将包含一个带有 true 的条目对于失败的 future ,另一个条目为 false成功者的关键。然后您可以检查这 2 个条目以采取相应的行动。

请注意,与您的原始代码相比有 2 个细微变化:

  • requestCompletableFuture现在是 CompletableFuture<RoomTypes.RoomType>
  • thenApply(responses::add)responses名单已删除

关于日志记录/异常处理,只需添加相关的requestCompletableFuture.handle()即可单独记录它们,但保留 requestCompletableFuture而不是 handle() 产生的结果.

关于java - 循环中的 CompletableFuture : How to collect all responses and handle errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51139489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com