CloseableHttpClient的使用和优化 上篇文章介绍了如何对Http请求进行优化,提到了异步
同步和异步的介绍、使用场景 下篇文章介绍了同步和异步的使用场景
本文就是对异步代码的介绍:
//Basic认证
private static final CredentialsProvider credsProvider = new BasicCredentialsProvider();
//异步HTTP请求配置
private static final RequestConfig reqestConfig;
//异步http请求客户端
private static final CloseableHttpAsyncClient httpClient;
//异步get方法
private static final HttpGet httpGet;
//jackson解析工具
private static final ObjectMapper mapper = new ObjectMapper();
static {
System.setProperty("http.maxConnections","50");
System.setProperty("http.keepAlive", "true");
//初始化BASE认证配置
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
new UsernamePasswordCredentials(“”,“”));
//初始化HTTP请求配置
reqestConfig = RequestConfig.custom()
.setContentCompressionEnabled(true)
.setSocketTimeout(100)
.setAuthenticationEnabled(true)
.setConnectionRequestTimeout(100)
.setConnectTimeout(100).build();
//关闭httpClient
httpClient = HttpAsyncClients.custom()
.useSystemProperties()
.setMaxConnTotal(50)
.setDefaultCredentialsProvider(credsProvider).build();
httpClient.start();
httpGet = new HttpGet();
httpGet.setConfig(reqestConfig);
}
/*
* 功能:返回HTTP GET
* @author zhangdaquan
* @date 2019/1/2 下午8:31
* @param [url]
* @return org.apache.http.client.methods.HttpGet
* @exception
*/
public static HttpGet get(String url) throws URISyntaxException {
httpGet.setURI(new URI(url));
return httpGet;
}
/*
* 功能:异步获取结果
* @author zhangdaquan
* @date 2019/1/2 下午8:32
* @param [url]
* @return void
* @exception
*/
public static Future<HttpResponse> getUrl(String url) throws IOException, HttpException, URISyntaxException {
HttpGet get = get(url);
Future<HttpResponse> httpResponseFuture = httpClient.execute(get, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse httpResponse) {
}
@Override
public void failed(Exception e) {
}
@Override
public void cancelled() {
}
});
return httpResponseFuture;
}
public static void main(String[] args) throws IOException, HttpException, ExecutionException, InterruptedException, URISyntaxException {
Long tm = System.currentTimeMillis();
for (int i = 0; i < 50 ; i++){
new Thread(()->{
try{
HttpResponse httpResponse = getUrl(getUrl).get();
HttpEntity entity = httpResponse.getEntity();
System.out.println(entity);
String s = EntityUtils.toString(entity);
//这里没有很好的处理response会导致上层业务要处理httpResponse
HttpClientUtils.closeQuietly(httpResponse);
System.out.println(s);
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
System.out.println(System.currentTimeMillis()-tm);*/
}