• 一、简介
  • 二、mvn依赖
  • 三、客户端
    • 3.1 官网实例
    • 3.2. 根据官方文档的介绍,简单封装了一个异步HttpClient工具类
    • 3.3 基本原理
  • 四、参考文档

一、简介

HttpClient提供了两种I/O模型:经典的java阻塞I/O模型和基于Java NIO的异步非阻塞事件驱动I/O模型。

Java中的阻塞I/O是一种高效、便捷的I/O模型,非常适合并发连接数量相对适中的高性能应用程序。只要并发连接的数量在1000个以下并且连接大多忙于传输数据,阻塞I/O模型就可以提供最佳的数据吞吐量性能。然而,对于连接大部分时间保持空闲的应用程序,上下文切换的开销可能会变得很大,这时非阻塞I/O模型可能会提供更好的替代方案。 异步I/O模型可能更适合于比较看重资源高效利用、系统可伸缩性、以及可以同时支持更多HTTP连接的场景。

二、mvn依赖

httpclient在4.x之后开始提供基于nio的异步版本httpasyncclient,httpasyncclient借助了Java并发库和nio进行封装(虽说NIO是同步非阻塞IO,但是HttpAsyncClient提供了回调的机制,与netty类似,所以可以模拟类似于AIO的效果),其调用方式非常便捷.

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.4</version>
</dependency>

三、客户端

 3.1 官网实例

CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
// Start the client
httpclient.start(); // Execute request
final HttpGet request1 = new HttpGet("http://www.apache.org/");
Future<HttpResponse> future = httpclient.execute(request1, null);
// and wait until a response is received
HttpResponse response1 = future.get();
System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine()); // One most likely would want to use a callback for operation result
final CountDownLatch latch1 = new CountDownLatch(1);
final HttpGet request2 = new HttpGet("http://www.apache.org/");
httpclient.execute(request2, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response2) {
latch1.countDown();
System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine());
} 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(); // In real world one most likely would also want to stream
// request and response body content
final CountDownLatch latch2 = new CountDownLatch(1);
final HttpGet request3 = new HttpGet("http://www.apache.org/");
HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3);
AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() { HttpResponse response; @Override
protected void onResponseReceived(final HttpResponse response) {
this.response = response;
} @Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
// Do something useful
} @Override
protected void releaseResources() {
} @Override
protected HttpResponse buildResult(final HttpContext context) {
return this.response;
} };
httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response3) {
latch2.countDown();
System.out.println(request3.getRequestLine() + "->" + response3.getStatusLine());
} public void failed(final Exception ex) {
latch2.countDown();
System.out.println(request3.getRequestLine() + "->" + ex);
} public void cancelled() {
latch2.countDown();
System.out.println(request3.getRequestLine() + " cancelled");
} });
latch2.await(); } finally {
httpclient.close();
}

3.2. 根据官方文档的介绍,简单封装了一个异步HttpClient工具类

public class AsyncHttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(AsyncHttpClientUtil.class);
//从池中获取链接超时时间(ms)
private static final int CONNECTION_REQUEST_TIMEOUT = 10000;
//建立链接超时时间(ms)
private static final int CONNECT_TIMEOUT = 10000;
//读取超时时间(ms)
private static final int SOCKET_TIMEOUT = 5000;
//连接数
private static final int MAX_TOTAL = 50;
private static final int MAX_PER_ROUTE = 50; private static final CloseableHttpAsyncClient httpclient;
private static PoolingNHttpClientConnectionManager poolManager; static {
httpclient=init();
httpclient.start();
} private static CloseableHttpAsyncClient init() {
CloseableHttpAsyncClient client=null;
try {
//配置io线程
IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setSoKeepAlive(true)
.build();
//创建一个ioReactor
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
// poolManager=new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor());
poolManager=new PoolingNHttpClientConnectionManager(ioReactor);
//设置连接池大小
poolManager.setMaxTotal(MAX_TOTAL);
poolManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build(); client= HttpAsyncClients.custom()
.setConnectionManager(poolManager)
.setDefaultRequestConfig(requestConfig)
.build();
return client;
} catch (IOReactorException e) {
e.printStackTrace();
}
return client;
} public static String get(String url, List<NameValuePair> ns) {
HttpGet httpget;
URIBuilder uri = new URIBuilder();
try {
if (ns!=null){
uri.setPath(url);
uri.addParameters(ns);
httpget = new HttpGet(uri.build());
}else{
httpget = new HttpGet(url);
} // One most likely would want to use a callback for operation result
httpclient.execute(httpget, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) {
System.out.println(httpget.getRequestLine() + "->" + response.getStatusLine());
try {
System.out.println("当前请求状态:"+poolManager.getTotalStats()+", response="+EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
} public void failed(final Exception ex) {
System.out.println(httpget.getRequestLine() + "->" + ex);
} public void cancelled() {
System.out.println(httpget.getRequestLine() + " cancelled");
} }); }catch (Exception e){
logger.error("[发送get请求失败]URL:{},异常:",uri.getUserInfo(), e);
}
return null;
} public static void main(String[] args) {
for (int i=0; i<10;i++){
System.out.println("第" + i +"次:");
get("http://httpbin.org/get",null);
}
}
}

3.3 基本原理

HTTPAysncClient 最后使用的是 InternalHttpAsyncClient,在 InternalHttpAsyncClient 中有个 ConnectionManager,这个就是我们管理连接的管理器。

而在 httpAsync 中只有一个实现那就是 PoolingNHttpClientConnectionManager。这个连接管理器中有两个我们比较关心的,一个是 Reactor,一个是 Cpool:

  • Reactor:所有的 Reactor 这里都是实现了 IOReactor 接口。在 PoolingNHttpClientConnectionManager 中会有拥有一个 Reactor,那就是 DefaultConnectingIOReactor,这个 DefaultConnectingIOReactor,负责处理 Acceptor。

在 DefaultConnectingIOReactor 有个 excutor 方法,生成 IOReactor 也就是我们图中的 BaseIOReactor,进行 IO 的操作。

  • CPool:在 PoolingNHttpClientConnectionManager 中有个 CPool,主要是负责控制我们连接,我们上面所说的 maxTotal 和 defaultMaxPerRoute,都是由其进行控制。

如果每个路由有满了,它会断开最老的一个链接;如果总共的 total 满了,它会放入 leased 队列,释放空间的时候就会将其重新连接。

关于Reactor可参考: https://www.cnblogs.com/doit8791/p/7461479.html

四、参考文档

  1. http://hc.apache.org/httpcomponents-asyncclient-4.1.x/index.html
  2. http://hc.apache.org/httpcomponents-asyncclient-4.1.x/httpasyncclient/xref/index.html
  3. http://ifeve.com/httpclient-async-call/
  4. https://blog.csdn.net/ouyang111222/article/details/78884634

异步httpClient(Async HttpClient)的更多相关文章

  1. MVC+Spring.NET+NHibernate .NET SSH框架整合 C# 委托异步 和 async /await 两种实现的异步 如何消除点击按钮时周围出现的白线? Linq中 AsQueryable(), AsEnumerable()和ToList()的区别和用法

    MVC+Spring.NET+NHibernate .NET SSH框架整合   在JAVA中,SSH框架可谓是无人不晓,就和.NET中的MVC框架一样普及.作为一个初学者,可以感受到.NET出了MV ...

  2. C#异步编程----async和await组合的写法

    微软示例: private async void StartButton_Click(object sender, RoutedEventArgs e) { // ExampleMethodAsync ...

  3. 抓住异步编程async/await语法糖的牛鼻子: SynchronizationContext

    长话短说,本文带大家抓住异步编程async/await语法糖的牛鼻子: SynchronizationContext 引言 C#异步编程语法糖async/await,使开发者很容易就能编写异步代码. ...

  4. 温故知新,CSharp遇见异步编程(Async/Await),聊聊异步编程最佳做法

    什么是异步编程(Async/Await) Async/Await本质上是通过编译器实现的语法糖,它让我们能够轻松的写出简洁.易懂.易维护的异步代码. Async/Await是C# 5引入的关键字,用以 ...

  5. 如何避免让线程摸鱼,请用异步技术 async await 拿捏他~

    发现问题 你点了外卖后,会一直不做其它事情,一直等外卖的到来么? 当然不会拉! 我们来看看代码世界的: public void Query(){ // 当前线程 向 数据库服务器 发起查询命令 // ...

  6. 新旧apache HttpClient 获取httpClient方法

    在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...

  7. 异步编程Async/await关键字

    异步编程Async \await 关键字在各编程语言中的发展(出现)纪实. 时间 语言版本 2012.08.15 C#5.0(VS2012) 2015.09.13 Python 3.5 2016.03 ...

  8. spring boot / cloud (四) 自定义线程池以及异步处理@Async

    spring boot / cloud (四) 自定义线程池以及异步处理@Async 前言 什么是线程池? 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线 ...

  9. C++笔记-并发编程 异步任务(async)

    转自 https://www.cnblogs.com/diysoul/p/5937075.html 参考:https://zh.cppreference.com/w/cpp/thread/lock_g ...

  10. c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习

    c#中@标志的作用   参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

随机推荐

  1. MySQL运维11-Mycat分库分表之应用指定分片

    一.应用指定分片 此规则是在运行阶段有应用自主决定路由到那个分片,根据提供的字段,然后按照指定的规则,截取该字段的部分子字符串当做分片的依据,该分别方法比较灵活,适用于某个字段有几个特殊的字符串拼接而 ...

  2. 51Nod 1085 01背包

    01背包入门题,刚学完当写模板. 在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2--Wn(Wi为整数),与之相对应的价值为P1,P2--Pn(Pi为整数).求背包能够容纳的最大价 ...

  3. 『UniApp』uni-app-打包成App

    前言 大家好,我是 BNTang, 在上一节文章中,我给大家详细的介绍了如何将我开发好的项目打包为微信小程序并且发布到微信小程序商店 趁热打铁,在来一篇文章,给大家详细的介绍如何将项目打包成APP. ...

  4. Halo新年灯笼-halonewyaer

    title: Halo新年灯笼 date: 2021-12-29 15:49:34.665 updated: 2022-03-10 16:00:53.189 url: https://www.yby6 ...

  5. 一个WPF版的Layui前端UI库

    前言 相信做.NET后端开发的很多小伙伴都用过Layui前端UI组件库,今天我们分享一个WPF版的Layui前端UI样式库:Layui-WPF. WPF介绍 WPF 是一个强大的桌面应用程序框架,用于 ...

  6. 记一次windows病毒联合排查全过程

    8月2日通过态势感知平台,发现大量内部DNS服务器有恶意请求,且告警描述为:试图解析僵尸网络C&C服务器xmr-eu2.nanopool.org的地址,通过截图可以看到,用户每5分钟会定期向目 ...

  7. 设置CentOS7使用代理服务器上网

    用三种方法设置CentOS7使用代理服务器上网 https://zhangyujia.cn/?p=1206 https://www.cnblogs.com/a-du/p/8964048.html 一. ...

  8. 【云原生 | Kubernetes 系列】— Kubernetes存储方案

    目录 [云原生 | Kubernetes 系列]- Kubernetes存储方案 一.基本存储 EmptyDir HostPath NFS 搭建nfs服务器 二.高级存储 PV和PVC pv pvc ...

  9. 文心一言 VS 讯飞星火 VS chatgpt (177)-- 算法导论13.3 6题

    六.用go语言,说明如果红黑树的表示中不提供父指针,应当如何有效地实现 RB-INSERT. 文心一言: 红黑树是一种自平衡的二叉搜索树,其中每个节点都包含一个颜色属性(红色或黑色),并且满足以下性质 ...

  10. Visual Studio 2022 Preview设置简体中文

    前言: 作为尝鲜小分队队长,对于vs的升级版Visual Studio 2022 Preview肯定也开始用上了,不过之前一直以为还没有出中文的语言包所以一直用的是英文版的,搞得英文本来不好的我很是不 ...