1

我正在尝试使用 Jetty 9 HttpClient API 开发一个高负载生成异步 HttpClient。我已经编写了执行 POST 请求的基本代码

public void connectHttp() throws Exception {
    HttpClient client = new HttpClient();       
    // Configure HttpClient here
    client.setMaxConnectionsPerDestination(1000);       

    try {
        client.start();
    } catch(Exception e) {
        System.out.println("Caught Exception in Client Start : ");
        e.printStackTrace();
        throw e;
    }
    try {
        for(int i = 0 ; i<1000;i++) {
            client.POST("http://localhost:8080/privaterestservice/jersey/privatedata/writedata")
            .timeout(3, TimeUnit.SECONDS)
            .file(Paths.get("stats_kestrel.txt"),"text/plain").send(new BufferingResponseListener() {
                @Override
                public void onComplete(Result res) {
                    System.out.println("Got Response : "+res.isSucceeded());
                                        }
            });         
        }

    }
    finally {
        //client.stop();
    }
    System.out.println("I am Done!!");
    System.out.println(client.getState());
}

我需要用大量请求轰炸服务器。但是当我运行这段代码时,最后几个请求失败了。我使用Jmeter检查,服务器没有问题。即使在所有请求完成后,代码也不会停止。

如何在收到所有响应后退出代码而不是线程进入睡眠状态?

任何帮助是极大的赞赏 :)

4

1 回答 1

5

您应该使用 CountDownLatch,例如:

public void connectHttp() throws Exception {
    HttpClient client = new HttpClient();       
    // Configure HttpClient here
    client.setMaxConnectionsPerDestination(1000);       
    CountDownLatch countDown = new CountDownLatch(1000);
    try {
        client.start();
    } catch(Exception e) {
        System.out.println("Caught Exception in Client Start : ");
        e.printStackTrace();
        throw e;
    }
    try {
        for(int i = 0 ; i<1000;i++) {
            client.POST("http://localhost:8080/privaterestservice/jersey/privatedata/writedata")
            .timeout(3, TimeUnit.SECONDS)
            .file(Paths.get("stats_kestrel.txt"),"text/plain").send(new BufferingResponseListener() {
                @Override
                public void onComplete(Result res) {
                    System.out.println("Got Response : "+res.isSucceeded());
                    countDown.countDown();
                }

                @Override
                public void onFailure(Response response, Throwable failure) {
                    countDown.countDown();
                }
            });         
        }

    }
    finally {
        //client.stop();
    }
    countDown.await();
    System.out.println("I am Done!!");
    System.out.println(client.getState());
}

它将等到所有响应完成。

于 2013-10-16T06:43:03.693 回答