?
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 发表
不错有用