我正在尝试为 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);
}
原文由 Rudrani Angira 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以简单地使用
allOf()
获得一个在所有初始期货完成(例外或未完成)时完成的未来,然后使用Collectors.partitioningBy()
在成功和失败之间拆分它们:生成的映射将包含一个带有
true
的条目用于失败的期货,另一个条目带有false
键用于成功的期货。然后您可以检查这 2 个条目以采取相应的行动。请注意,与您的原始代码相比有 2 个细微变化:
requestCompletableFuture
现在是CompletableFuture<RoomTypes.RoomType>
thenApply(responses::add)
和responses
列表已删除关于日志记录/异常处理,只需添加相关的
requestCompletableFuture.handle()
以单独记录它们,但保留requestCompletableFuture
而不是handle()
产生的结果。