CompletableFuture in loop:如何收集所有响应并处理错误
2022-09-02 19:58:38
我正在尝试在循环中调用 rest api 以获取请求。每个调用都是一个 .每个 api 调用返回一个对象类型PUT
CompletableFuture
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);
}