使用Jetty 9 HttpClient的异步POST请求

时间:2013-10-14 18:00:26

标签: java

我正在尝试使用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检查了服务器没有问题。即使在完成所有请求之后,代码也不会停止。

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

非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:4)

您应该使用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());
}

它将等待所有回复完成。