我有一份即将加入的可完成期货的清单,以同时获得所有结果。我使用了CompletableFuture.allOf()
。但是,使用此结果可以输入CompletableFuture<List<Object>>
。我需要将其转换为我创建的对象。我想从API调用返回结果。我该怎么办?
在过去的两天中,我已经对所有示例进行了研究,但仍然找不到解决方法。
public CompletableFuture<ResponseEntity<Bmwvehiclemain>> getVehicle(String rfidtag){
ExecutorService vehicleRequestExecutor = Executors.newFixedThreadPool(50);
String url="";
String authString= "user"+":"+"password";
byte[] encodedAuth= Base64.encodeBase64(authString.getBytes(Charset.forName("US-ASCII")));
String authHeader="Basic "+new String(encodedAuth);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set("Authorization", authHeader);
HttpEntity<Bmwvehiclemain> requestEntity=new HttpEntity <Bmwvehiclemain>(headers);
Bmwvehiclemain v=new Bmwvehiclemain("notindb");
CompletableFuture<ResponseEntity<Bmwvehiclemain>> future= CompletableFuture
.supplyAsync(()-> appRestTemplate.exchange(url + rfidtag, HttpMethod.GET, requestEntity, Bmwvehiclemain.class), vehicleRequestExecutor)
.thenApply((responseEntity)->{
return responseEntity;
})
.exceptionally(ex ->{
return new ResponseEntity<>(v, HttpStatus.OK);
});
return future;
}
public void vehicleRequests(List<Maybevehicle> vehicles){
List<CompletableFuture<?>> completableFutures = new ArrayList<>(vehicles.size());
List<Bmwvehiclemain> foundVehs= new ArrayList<>();
for (Maybevehicle v : vehicles) {
CompletableFuture<?> requestCompletableFuture=getVehicle(v.getB().getRfidtag());
if (requestCompletableFuture !=null){
completableFutures.add(requestCompletableFuture);
}
}
try {
CompletableFuture<Void> allFutures=CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])); /
CompletableFuture<List<Object>> allPageContentsFuture = allFutures.thenApply(future -> {
return completableFutures.stream()
.map(completableFuture -> completableFuture.join())
.collect(Collectors.toList());
});
} catch (CompletionException | NullPointerException | InterruptedException e){
e.printStackTrace();
}
}
我想从API rest模板调用返回结果。我希望将结果添加到Bmwvehiclemain对象列表中。