我试图使用HttpAsyncClient通过每秒提交一百或数千个HTTP请求并对每个请求的响应计时来压力测试我的Web应用程序。我的代码基于this quickstart guide,但是似乎连接到服务器并发送HTTP请求的线程然后坐在那里等待服务器的响应!相反,我希望它继续发送下一个HTTP请求,而不必等待HTTP响应。

这是我的测试代码:

public class TestAsyncHttpRequest {

    private static final SimpleDateFormat FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd hh:mm:ss.SSS");

    public static void main(String[] args) throws Exception {

        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
        try {
            // Start the client
            httpclient.start();
            final CountDownLatch latch = new CountDownLatch(100);
            for (int i = 0; i < 100; i++) {
                System.out.println("Sending POST request at "
                        + FORMAT.format(new Date()));
                final HttpPost request = new HttpPost(
                        "http://localhost:8080/test");
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                    }

                    public void cancelled() {
                        latch.countDown();
                    }

                });
                Thread.sleep(50);
            }
            latch.await();
        } finally {
            httpclient.close();
        }
    }
}


相应的测试servlet仅打印请求的时间,然后休眠20秒:

public class TestServlet extends HttpServlet {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        getServletContext().log(
                "TestServlet Received POST at: " + fmt.format(new Date()));
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}


servlet输出如下-请注意,它每20秒仅接收两个请求:

INFO: TestServlet Received POST at: 2014-03-28 07:01:16.838
INFO: TestServlet Received POST at: 2014-03-28 07:01:16.838
INFO: TestServlet Received POST at: 2014-03-28 07:01:36.873
INFO: TestServlet Received POST at: 2014-03-28 07:01:36.873
INFO: TestServlet Received POST at: 2014-03-28 07:01:56.881
INFO: TestServlet Received POST at: 2014-03-28 07:01:56.881
INFO: TestServlet Received POST at: 2014-03-28 07:02:16.891
INFO: TestServlet Received POST at: 2014-03-28 07:02:16.891


是否有一些配置选项可以使我向服务器发送一千个HTTP请求而不会产生大量线程?

最佳答案

HttpAsyncClient对并发连接总数和每个主机的并发连接数目有限制。

尝试增加它们:

CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
    .setMaxConnTotal(100)
    .setMaxConnPerRoute(100)
    .build();

关于java - 如何使HttpAsyncClient异步执行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22712059/

10-10 08:45