二十七、CloseableHttpAsyncClient的使用和优化
CloseableHttpClient的使用和优化 上篇文章介绍了如何对Http请求进行优化,提到了异步
【二十七、CloseableHttpAsyncClient的使用和优化】同步和异步的介绍、使用场景 下篇文章介绍了同步和异步的使用场景
本文就是对异步代码的介绍:
//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 getUrl(String url) throws IOException, HttpException, URISyntaxException {
HttpGet get = get(url);
Future httpResponseFuture = httpClient.execute(get, new FutureCallback() {
@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);
*/
}
推荐阅读
- 一个人的碎碎念
- 野营记-第五章|野营记-第五章 讨伐梦魇兽
- Shell-Bash变量与运算符
- 清明,是追思、是传承、是感恩。
- 牛人进化+|牛人进化+ 按自己的意愿过一生
- 七老修复好敏感、角质层薄、红血丝
- 华为旁!大社区、地铁新盘,佳兆业城市广场五期!
- 迷失的世界(二十七)
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。
- 螃蟹和这些食物同吃,轻则腹泻、重则中毒!要小心哦~