1

我正在尝试异步发出 x 数量的 HTTP 请求。我看了问题Java中的异步IO?以及如何在 JAVA 中创建异步 HTTP 请求?. 我找到了很好的库Asynchronous Http and WebSocket Client library for Java,但我不明白如何安全地将多个结果组合成一个结果。例如,如果我有以下代码:

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 ???
}

如何安全地将这些结果合并到 List 中,并在所有请求完成后继续。

4

3 回答 3

2

我找到了使用期货的本教程。您可以执行以下操作:

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
于 2013-03-28T08:40:34.953 回答
0

您可以调用get()Future 类的方法来获取结果。请注意,对该方法的调用可能会阻塞,直到结果可用

于 2013-03-28T08:10:12.813 回答
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());
            }
        }
    }
}
于 2017-11-23T06:58:08.040 回答