`

HttpAsyncClient

阅读更多
参考:
http://wangxinchun.iteye.com/blog/2136254
http://wangxinchun.iteye.com/blog/2156660
http://wangxinchun.iteye.com/blog/2166837

调用http接口,是否可以异步?
答案当然是可以。

方案1:
httpclient+new Thread

/**
 * 使用thread + http 实现异步
 * @author wangxinchun1988@163.com
 * @date 2014-12-16下午5:29:26
 */
public class AsyncHttpClientUtil {
	public static void main(String[] args) throws Exception {
		HttpTask task = new HttpTask();
		task.setUrl("http://www.baidu.com");
		Thread t = new Thread(task);
		t.start();
		t.join();
		System.out.println(task.getData());
	}
	
	public static class HttpTask implements Runnable{
		private String url;
		private String data;

		public void run() {
			System.out.println(url);
			// 模拟请求http返回的结果
			data = "http response " + url;
		}

		public String getData() {
			return data;
		}

		public void setUrl(String url) {
			this.url = url;
		}
	}
}



优化版本:
/**
 * 使用thread + http 实现异步
 * 
 * @author wangxinchun1988@163.com
 * @date 2014-12-16下午5:29:26
 */
public class AsyncHttpClientUtil2 {
	public static void main(String[] args) throws Exception {
		CountDownLatch latch = new CountDownLatch(1);
		HttpTask task = new HttpTask(latch);
		task.setUrl("http://www.baidu.com");
		Thread t = new Thread(task);
		t.start();
		latch.await();
		System.out.println(task.getData());
	}

	public static class HttpTask implements Runnable {
		private String url;
		private String data;
		private CountDownLatch latch;

		public HttpTask(CountDownLatch latch) {
			this.latch = latch;
		}

		public void run() {
			System.out.println(url);
			// 模拟请求http返回的结果
			data = "http response " + url;
			latch.countDown();
		}

		public String getData() {
			return data;
		}

		public void setUrl(String url) {
			this.url = url;
		}
	}
}


方案2
使用apache 的AsyncHttpClient 方案
也是本次讲解的重点
maven 引用:
<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>${httpclient.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>${httpclient.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore-nio</artifactId>
			<version>4.3.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.3.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpasyncclient</artifactId>
			<version>4.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpasyncclient-cache</artifactId>
			<version>4.0.2</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.6</version>
		</dependency>
	</dependencies>



使用方式1:(适合调用后很快就会通过引用获取数据)
/**
 * 使用CloseableHttpAsyncClient返回Future<HttpResponse> 实现异步
 * 
 * @author wangxinchun1988@163.com
 * @date 2014-12-16下午5:29:26
 */
public class AsyncHttpClientUtil3 {
	   public static void main(String[] args) throws Exception {
	        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	        try {
	            // Start the client
	            httpclient.start();
	            // Execute request
	            final HttpGet request1 = new HttpGet("http://www.baidu.com/");
	            Future<HttpResponse> future = httpclient.execute(request1, null);
	            // and wait until response is received
	            HttpResponse response1 = future.get();
	            System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine() + " \n" 
	            + EntityUtils.toString(response1.getEntity()));
	        }catch(Exception e){
	        	e.printStackTrace();
	        }finally{
	        	if(httpclient != null){
	        		httpclient.close();
	        	}
	        }
	   }
}


方式2:(适合在回调存储特定的数据)
public class AsyncHttpClientUtil4 {
	public static void main(String[] args) throws Exception {
		CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
		httpclient.start();
		final CountDownLatch latch1 = new CountDownLatch(1);
		final HttpGet request2 = new HttpGet("http://www.baidu.com/");
		final ObjectHolder<HttpResponse> holder = new ObjectHolder<HttpResponse>();
		httpclient.execute(request2, new FutureCallback<HttpResponse>() {

			public void completed(final HttpResponse response2) {
				holder.setData(response2);
				System.out.println(request2.getRequestLine() + "->"+ response2.getStatusLine());
				latch1.countDown();
			}

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

			public void cancelled() {
				latch1.countDown();
				System.out.println(request2.getRequestLine() + " cancelled");
			}
		});
		latch1.await();
		HttpResponse response = holder.getData();
		System.out.println(EntityUtils.toString(response.getEntity()));
	}

	public static class ObjectHolder<T> {
		private T data;

		public T getData() {
			return data;
		}

		public void setData(T data) {
			this.data = data;
		}
	}
}


进阶批量:
public class AsyncClientHttpExchangeFutureCallback {

    public static void main(final String[] args) throws Exception {
        RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(3000) .setConnectTimeout(3000).build();
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
            .setDefaultRequestConfig(requestConfig).build();
        try {
            httpclient.start();
            final HttpGet[] requests = new HttpGet[] {
                    new HttpGet("http://www.apache.org/"),
                    new HttpGet("https://www.verisign.com/"),
                    new HttpGet("http://www.google.com/")
            };
            final CountDownLatch latch = new CountDownLatch(requests.length);
            final Map<String,HttpResponse> resultContain = new HashMap<String,HttpResponse>();
            for (final HttpGet request: requests) {
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

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

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

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

                });
            }
            latch.await();
            
            for(Map.Entry<String, HttpResponse> item : resultContain.entrySet()){
            	System.out.println(item.getKey()+":  "+EntityUtils.toString(item.getValue().getEntity()));
            }
            
            System.out.println("Shutting down");
        } finally {
            httpclient.close();
        }
        System.out.println("Done");
    }

}
1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics