2013-03-28 60 views
1

我試圖使x請求數量異步。我看了問題Asynchronous IO in Java?How do you create an asynchronous HTTP request in JAVA?。我發現好的圖書館Asynchronous Http and WebSocket Client library for Java,但我不明白我如何可以安全地將多個結果合併成一個結果。例如,如果我有下面的代碼:如何將異步HTTP請求響應組合到一個?

AsyncHttpClient c = new AsyncHttpClient(); 
List<String> urls = getUrls(); 
List<MyResultObject> results = new ArrayList<>(); 
for(String url : urls) 
{ 
    // Create asynchronous request 
    Future<MyResultObject> f = c.prepareGet(url).execute(handler); 

    // How can I add completed responses to my results list ??? 
} 

我怎樣才能安全地這些結果組合成列表,並在所有的請求都完成繼續。

回答

2

我找到了使用期貨的this tutorial。您可以執行以下操作:

AsyncHttpClient c = new AsyncHttpClient(); 
List<String> urls = getUrls(); 
List<Future<MyResultObject>> futures = new ArrayList<>(); // keep track of your futures 
List<MyResultObject> results = new ArrayList<>(); 
for(String url : urls) 
{ 
    // Create asynchronous request 
    Future<MyResultObject> f = c.prepareGet(url).execute(handler); 
    futures.add(f); 
} 

// Now retrieve the result 
for (Future<MyResultObject> future : futures) { 
    try { 
    results.add(future.get()); 
    } catch (InterruptedException e) { 
    e.printStackTrace(); 
    } catch (ExecutionException e) { 
    e.printStackTrace(); 
    } 
} 
// continue with your result list 
0

你可以調用Future類的get()方法來獲得結果。請注意,對該方法的調用可能會阻止,直到結果可用

0

如果要合併幾個http請求並獲取所有結果。 你可以看看代碼打擊。

package ParallelTasks; 

import org.apache.commons.lang3.tuple.MutablePair; 
import org.apache.commons.lang3.tuple.Pair; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.*; 

public class ParallelHttpRequest { 
    //thread pool to execute http request task. 
    static final ExecutorService businessRequestExecutor = Executors.newCachedThreadPool(); 


    public static void main(String[] args) throws InterruptedException, ExecutionException { 
     List<String> urlList = new ArrayList<String>(); 

     final CountDownLatch latch = new CountDownLatch(urlList.size()); 

     List<Future<Pair<String, String>>> list = new ArrayList<Future<Pair<String, String>>>(); 
     for (final String url : urlList) { 
      Future<Pair<String, String>> future = businessRequestExecutor.submit(new Callable<Pair<String, String>>() { 
       public Pair<String, String> call() throws Exception { 
        try { 
         //do post or get http request here. 
         //SoaHttpUtil.post(config.getUrl(), buReqJson); 

         String result = ""; 

         return new MutablePair<String, String>(url, result); 
        } catch (Exception ex) { 
         System.out.println(ex); 
         return new MutablePair<String, String>(url, null); 
        } finally { 
         latch.countDown(); 
        } 
       } 
      }); 
      list.add(future); 
     } 

     //wait no more than 5 seconds. 
     latch.await(5000, TimeUnit.MILLISECONDS); 

     //print finished request's result. 
     for (Future<Pair<String, String>> future : list) { 
      if (future.isDone()) { 
       System.out.println(future.get().getValue()); 
      } 
     } 
    } 
}