[英]Play2 calling multiple webservices with AsyncResult (Java)
我有一个使用Java的Play 2.1控制器,我需要调用一个外部Web服务来获取一些数据。 然后,使用此数据结果,我必须使用n个调用来调用另一个Web服务,这与第一个Webservice调用中的n个结果相对应。
对于性能问题,我想使用Promise在单独的线程中进行n次调用。
所以我会有这样的循环:
List<String> firstResults = WS.url("http://...") ///...blablabla
for(String keyword : firstResults){
Promise<ResultType> promise = play.libs.Akka.future(
new Callable<ResultType>() {
public Integer call() {
return //...
}
}
);}
如何同步n个诺言,然后使用Async API在一个响应(所有结果的列表)中减少结果,然后仅在所有调用完成后才返回http响应?
无法知道呼叫数量使问题变得更加困难...(我无法将promise声明为promise1,promise2等。)
Promise.waitAll是您想要的:
List<String> firstResults = WS.url("http://...") ///...blablabla
List<Promise<? extends ResultType>> webServiceCalls = new ArrayList<>;
for(String keyword : firstResults){
Promise<ResultType> promise = WS.url("http://...?keyboard=" + keyword).get().map(
// function of Response to ResultType
);
webServiceCalls.add(promise);
}
// Don't be confused by the name here, it's not actually waiting
Promise<List<ResultType>> results = Promise.waitAll(webServiceCalls);
return async(results.map(new Function<List<ResultType, Result>>() {
public Result apply(List<ResultType> results) {
// Convert results to ResultType
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.