使用apache的httpclient进行http的交互处理已经很长时间了,而httpclient实例则使用了http链接池,想必你们也没有关心过链接池的管理。事实上,经过分析httpclient源码,发现它很优雅地隐藏了全部的链接池管理细节,开发者彻底不用花太多时间去思考链接池的问题。html
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(); }
好比:MaxtTotal=400,DefaultMaxPerRoute=200,而我只链接到http://hjzgg.com时,到这个主机的并发最多只有200;而不是400;而我链接到http://qyxjj.com 和 http://httls.com时,到每一个主机的并发最多只有200;即加起来是400(但不能超过400)。因此起做用的设置是DefaultMaxPerRoute。apache
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(); } }
http的长链接复用, 其断定规则主要分两类。
1. http协议支持+请求/响应header指定
2. 一次交互处理的完整性(响应内容消费干净)
对于前者, httpclient引入了ConnectionReuseStrategy来处理, 默认的采用以下的约定:api
org.apache.http.impl.client.DefaultClientConnectionReuseStrategy服务器
处理完请求后,获取到response,经过ConnectionReuseStrategy判断链接是否可重用,若是是经过ConnectionKeepAliveStrategy获取到链接最长有效时间,并设置链接可重用标记。并发
更多参考:https://www.cnblogs.com/mumuxinfei/p/9121829.htmlapp
HttpClientBuilder会构建一个InternalHttpClient实例,也是CloseableHttpClient实例。InternalHttpClient的doExecute方法来完成一次request的执行。dom
会继续调用MainClientExec的execute方法,经过链接池管理者获取链接(HttpClientConnection)。oop
构建ConnectionHolder类型对象,传递链接池管理者对象和当前链接对象。ui
请求执行完返回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实例处理请求,无需调用者手动释放链接。
@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; }
@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; }
@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()); }; } }
Apache的HttpClient组件可谓良心之做,细细的品味一下源码能够学到不少设计模式和比编码规范。不过在阅读源码以前最好了解一下不一样版本的HTTP协议,尤为是HTTP协议的Keep-Alive模式。使用Keep-Alive模式(又称持久链接、链接重用)时,Keep-Alive功能使客户端到服 务器端的链接持续有效,当出现对服务器的后继请求时,Keep-Alive功能避免了创建或者从新创建链接。这里推荐一篇参考连接:https://www.jianshu.com/p/49551bda6619。