HttpAsyncClient 做并发长连接的一个实例_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > HttpAsyncClient 做并发长连接的一个实例

HttpAsyncClient 做并发长连接的一个实例

 2014/4/11 18:29:59  jnwzping  程序员俱乐部  我要评论(0)
  • 摘要:importjava.util.concurrent.CountDownLatch;importorg.apache.http.HttpResponse;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.concurrent.FutureCallback;importorg.apache.http.impl
  • 标签:

?

class="java" name="code">import java.util.concurrent.CountDownLatch;

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;

public class AsyncClientHttpExchangeFutureCallback {

    public static void main(final String[] args) throws Exception {
        RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(300000)
            .setConnectTimeout(300000).build();
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
            .setDefaultRequestConfig(requestConfig).setMaxConnTotal(1000).setMaxConnPerRoute(1000)//此处为多并发设置
.build();
        try {
            httpclient.start();
            HttpGet[] requests  =new HttpGet[900];
            for (int i = 0; i < 900; i++) {
	           requests[i] = new HttpGet("http://192.168.71.192:8100/sub?cname="+i);
	           
            }
            final CountDownLatch latch = new CountDownLatch(requests.length+1);
            for (final HttpGet request: requests) {
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.out.println(request.getRequestLine() + "->" + ex);
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(request.getRequestLine() + " cancelled");
                    }

                });
            }
            latch.await();
            System.out.println("Shutting down");
        } finally {
            httpclient.close();
        }
        System.out.println("Done");
    }

}

?

?

  • 相关文章
    网友 2014/12/22 11:55:10 发表

    不错有用

发表评论
用户名: 匿名