2013-04-29 30 views
2

我在Java中有一個Play 2.1控制器,我需要調用外部web服務來獲取一些數據。然後用這個數據結果,我必須調用另一個帶有n個調用的Web服務,與第一個Web服務調用的n個結果相對應。Play2使用AsyncResult(Java)調用多個webservices

對於性能問題,我想使用承諾在分離的線程中進行n個調用。

所以我有這樣一個循環:使用異步API

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個承諾,然後降低一個響應(所有結果的列表)的結果,然後返回只有在所有呼叫完成後纔回應http響應?

不能夠知道呼叫的數量使問題更加困難......(我不能宣佈承諾爲promise1,promise2等)

回答

4

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 
    } 
}); 
+0

謝謝詹姆斯,這正是我所需要的! Scala Iteratee API中等效於「waitAll」的是什麼? – Loic 2013-04-30 06:59:02

+2

waitAll令人困惑的名字已解決,現在該方法被命名爲「sequence」:) – Loic 2013-04-30 13:23:58

+0

由於iteratees是從消費者產生結果的消費者,而不是將來的值,所以waitAll或序列並沒有意義一些迭代。但是,例如,您可以使用Enumeratee.zip或Enumeratee.zipWith來使兩個迭代消耗相同的流,並生成其結果的元組。 – 2013-05-01 03:48:43