我有一个RESTFul API,其响应包含很多字段。我需要在响应中添加其他字段,这些字段需要以异步方式从出站RESTFul API调用中获取其值。我需要调用API的请求参数包含在List<A>
中。在我的API流程中,List<A>
的每次迭代中都有很多业务逻辑,涉及一些数据库查询和一堆Java Map / List操作。因此,当服务执行其BAU时,我希望子线程执行出站API调用,提取所需的信息,将其设置在对象B中,并在每个主线程的末尾携带将在主线程中使用的B。我的列表的迭代。
下面是我使用CompletableFuture.supplyAsync()。thenApply()尝试过的代码。
for(A a: listA){
//at the beginning of the iteration
CompletableFuture<B> asyncB = ioSvcObject.getRequiredFields(a.getReqParam1(),a.getReqParm2())
...
The BAU goes here..
//towards the end of iteration
if(null != asyncB.get()){
..set data from B to response object..
}
}
现在我的ioSvcObject.getRequiredFields()方法看起来像这样:
public CompletableFuture<B> getRequiredFields(String param1,String param2){
return CompletableFuture.runAsync(() -> getapiresponseObj(param1,param2)).thenApply(obj -> getB(obj));
}
private D getapiresponseObj(String param1,String param2){
//calls the API using restTemplate.exchange()
return D;
}
private B getB(D d){
//gets the required fields from d and sets it to B and returns B
return B;
}
尽管我希望B在调用asyncB.get()
之前在asyncB中可用,但我无法排除在get()上等待/阻塞的机会。只是好奇是否有一种更好的方法来做到这一点而不会受到阻碍。请提出是否可以采取更好的方法。谢谢。