zoukankan      html  css  js  c++  java
  • apache的httpclient进行http的交互处理

    使用apache的httpclient进行http的交互处理已经很长时间了,而httpclient实例则使用了http连接池,想必大家也没有关心过连接池的管理。事实上,通过分析httpclient源码,发现它很优雅地隐藏了所有的连接池管理细节,开发者完全不用花太多时间去思考连接池的问题。

    2|0Apache官网例子

     

     
    CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { System.out.println(EntityUtils.toString(entity)); } else { // Stream content out } } } finally { response.close(); }
     

    3|0HttpClient及其连接池配置


    • 整个线程池中最大连接数 MAX_CONNECTION_TOTAL = 800
    • 路由到某台主机最大并发数,是MAX_CONNECTION_TOTAL(整个线程池中最大连接数)的一个细分 ROUTE_MAX_COUNT = 500
    • 重试次数,防止失败情况 RETRY_COUNT = 3
    • 客户端和服务器建立连接的超时时间 CONNECTION_TIME_OUT = 5000
    • 客户端从服务器读取数据的超时时间 READ_TIME_OUT = 7000
    • 从连接池中获取连接的超时时间 CONNECTION_REQUEST_TIME_OUT = 5000
    • 连接空闲超时,清楚闲置的连接 CONNECTION_IDLE_TIME_OUT = 5000
    • 连接保持存活时间 DEFAULT_KEEP_ALIVE_TIME_MILLIS = 20 * 1000

    4|0MaxtTotal和DefaultMaxPerRoute的区别


    • MaxtTotal是整个池子的大小;
    • DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分;

    比如:MaxtTotal=400,DefaultMaxPerRoute=200,而我只连接到http://hjzgg.com时,到这个主机的并发最多只有200;而不是400;而我连接到http://qyxjj.com 和 http://httls.com时,到每个主机的并发最多只有200;即加起来是400(但不能超过400)。所以起作用的设置是DefaultMaxPerRoute。

    5|0HttpClient连接池模型


    6|0HttpClient从连接池中获取连接分析


    org.apache.http.pool.AbstractConnPool

     
    private E getPoolEntryBlocking( final T route, final Object state, final long timeout, final TimeUnit tunit, final PoolEntryFuture<E> future) throws IOException, InterruptedException, TimeoutException { Date deadline = null; if (timeout > 0) { deadline = new Date (System.currentTimeMillis() + tunit.toMillis(timeout)); } this.lock.lock(); try { final RouteSpecificPool<T, C, E> pool = getPool(route);//这是每一个路由细分出来的连接池 E entry = null; while (entry == null) { Asserts.check(!this.isShutDown, "Connection pool shut down"); //从池子中获取一个可用连接并返回 for (;;) { entry = pool.getFree(state); if (entry == null) { break; } if (entry.isExpired(System.currentTimeMillis())) { entry.close(); } else if (this.validateAfterInactivity > 0) { if (entry.getUpdated() + this.validateAfterInactivity <= System.currentTimeMillis()) { if (!validate(entry)) { entry.close(); } } } if (entry.isClosed()) { this.available.remove(entry); pool.free(entry, false); } else { break; } } if (entry != null) { this.available.remove(entry); this.leased.add(entry); onReuse(entry); return entry; } //创建新的连接 // New connection is needed final int maxPerRoute = getMax(route);//获取当前路由最大并发数 // Shrink the pool prior to allocating a new connection final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute); if (excess > 0) {//如果当前路由对应的连接池的连接超过最大路由并发数,获取到最后使用的一次连接,释放掉 for (int i = 0; i < excess; i++) { final E lastUsed = pool.getLastUsed(); if (lastUsed == null) { break; } lastUsed.close(); this.available.remove(lastUsed); pool.remove(lastUsed); } } //尝试创建新的连接 if (pool.getAllocatedCount() < maxPerRoute) {//当前路由对应的连接池可用空闲连接数+当前路由对应的连接池已用连接数 < 当前路由对应的连接池最大并发数 final int totalUsed = this.leased.size(); final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0); if (freeCapacity > 0) { final int totalAvailable = this.available.size(); if (totalAvailable > freeCapacity - 1) {//线程池中可用空闲连接数 > (线程池中最大连接数 - 线程池中已用连接数 - 1) if (!this.available.isEmpty()) { final E lastUsed = this.available.removeLast(); lastUsed.close(); final RouteSpecificPool<T, C, E> otherpool = getPool(lastUsed.getRoute()); otherpool.remove(lastUsed); } } final C conn = this.connFactory.create(route); entry = pool.add(conn); this.leased.add(entry); return entry; } } boolean success = false; try { pool.queue(future); this.pending.add(future); success = future.await(deadline); } finally { // In case of 'success', we were woken up by the // connection pool and should now have a connection // waiting for us, or else we're shutting down. // Just continue in the loop, both cases are checked. pool.unqueue(future); this.pending.remove(future); } // check for spurious wakeup vs. timeout if (!success && (deadline != null) && (deadline.getTime() <= System.currentTimeMillis())) { break; } } throw new TimeoutException("Timeout waiting for connection"); } finally { this.lock.unlock(); } }
     

    7|0连接重用和保持策略


    http的长连接复用, 其判定规则主要分两类。
      1. http协议支持+请求/响应header指定
      2. 一次交互处理的完整性(响应内容消费干净)
      对于前者, httpclient引入了ConnectionReuseStrategy来处理, 默认的采用如下的约定:

    • HTTP/1.0通过在Header中添加Connection:Keep-Alive来表示支持长连接。
    • HTTP/1.1默认支持长连接, 除非在Header中显式指定Connection:Close, 才被视为短连接模式。

    7|1HttpClientBuilder创建MainClientExec


    7|2ConnectionReuseStrategy(连接重用策略) 


    org.apache.http.impl.client.DefaultClientConnectionReuseStrategy

    7|3MainClientExec处理连接


    处理完请求后,获取到response,通过ConnectionReuseStrategy判断连接是否可重用,如果是通过ConnectionKeepAliveStrategy获取到连接最长有效时间,并设置连接可重用标记。

    7|4连接重用判断逻辑


    • request首部中包含Connection:Close,不复用
    • response中Content-Length长度设置不正确,不复用
    • response首部包含Connection:Close,不复用
    • reponse首部包含Connection:Keep-Alive,复用
    • 都没命中的情况下,如果HTTP版本高于1.0则复用

    更多参考:https://www.cnblogs.com/mumuxinfei/p/9121829.html

    8|0连接释放原理分析


    HttpClientBuilder会构建一个InternalHttpClient实例,也是CloseableHttpClient实例。InternalHttpClient的doExecute方法来完成一次request的执行。

    会继续调用MainClientExec的execute方法,通过连接池管理者获取连接(HttpClientConnection)。

    构建ConnectionHolder类型对象,传递连接池管理者对象和当前连接对象。

    请求执行完返回HttpResponse类型对象,然后包装成HttpResponseProxy对象(是CloseableHttpResponse实例)返回。

    CloseableHttpClient类其中一个execute方法如下,finally方法中会调用HttpResponseProxy对象的close方法释放连接。

    最终调用ConnectionHolder的releaseConnection方法释放连接。

    CloseableHttpClient类另一个execute方法如下,返回一个HttpResponseProxy对象(是CloseableHttpResponse实例)。 

    这种情况下调用者获取了HttpResponseProxy对象,可以直接拿到HttpEntity对象。大家关心的就是操作完HttpEntity对象,使用完InputStream到底需不需要手动关闭流呢?

    其实调用者不需要手动关闭流,因为HttpResponseProxy构造方法里有增强HttpEntity的处理方法,如下。

    调用者最终拿到的HttpEntity对象是ResponseEntityProxy实例。

    ResponseEntityProxy重写了获取InputStream的方法,返回的是EofSensorInputStream类型的InputStream对象。

    EofSensorInputStream对象每次读取都会调用checkEOF方法,判断是否已经读取完毕。

    checkEOF方法会调用ResponseEntityProxy(实现了EofSensorWatcher接口)对象的eofDetected方法。

    EofSensorWatcher#eofDetected方法中会释放连接并关闭流。

    综上,通过CloseableHttpClient实例处理请求,无需调用者手动释放连接。

    9|0HttpClient在Spring中应用


    9|1创建ClientHttpRequestFactory


     
    @Bean public ClientHttpRequestFactory clientHttpRequestFactory() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build(); httpClientBuilder.setSSLContext(sslContext) .setMaxConnTotal(MAX_CONNECTION_TOTAL) .setMaxConnPerRoute(ROUTE_MAX_COUNT) .evictIdleConnections(CONNECTION_IDLE_TIME_OUT, TimeUnit.MILLISECONDS); httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, true)); httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); CloseableHttpClient client = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(client); clientHttpRequestFactory.setConnectTimeout(CONNECTION_TIME_OUT); clientHttpRequestFactory.setReadTimeout(READ_TIME_OUT); clientHttpRequestFactory.setConnectionRequestTimeout(CONNECTION_REQUEST_TIME_OUT); clientHttpRequestFactory.setBufferRequestBody(false); return clientHttpRequestFactory; }
     

    9|2创建RestTemplate


     
    @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory()); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 修改StringHttpMessageConverter内容转换器 restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); return restTemplate; }
     

    9|3 Spring官网例子


     
    @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { SpringApplication.run(Application.class); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public CommandLineRunner run(RestTemplate restTemplate) throws Exception { return args -> { Quote quote = restTemplate.getForObject( "https://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); }; } }
     

    10|0总结


    Apache的HttpClient组件可谓良心之作,细细的品味一下源码可以学到很多设计模式和比编码规范。不过在阅读源码之前最好了解一下不同版本的HTTP协议,尤其是HTTP协议的Keep-Alive模式。使用Keep-Alive模式(又称持久连接、连接重用)时,Keep-Alive功能使客户端到服 务器端的连接持续有效,当出现对服务器的后继请求时,Keep-Alive功能避免了建立或者重新建立连接。这里推荐一篇参考链接:https://www.jianshu.com/p/49551bda6619。


    __EOF__

    作  者:胡峻峥
    出  处:https://www.cnblogs.com/hujunzheng/p/11629198.html
    关于博主:编程路上的小学生,热爱技术,喜欢专研。评论和私信会在第一时间回复。或者直接私信我。
    版权声明:署名 - 非商业性使用 - 禁止演绎,协议普通文本 | 协议法律文本
    声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐】一下。您的鼓励是博主的最大动力!

     
    分类: HTTP
  • 相关阅读:
    Scala (三)集合
    为什么成为一名程序员?
    Hadoop——Yarn
    Redis(一)NoSQL简介、Redis安装 、数据类型、配置文件、发布订阅
    Java并发编程——共享模型之内存( JMM、原子性、可见性、有序性、volatile原理)
    KafkaAPI实战案例
    分布式技术原理笔记(二)分布式体系结构
    Flume 进阶
    Kafka框架基础
    Scala (二)面向对象
  • 原文地址:https://www.cnblogs.com/xichji/p/11633394.html
Copyright © 2011-2022 走看看