HttpComponents HttpClient连接池(6)-连接清理

上一篇文章里我们介绍了 httpclient 连接池中连接的可用性检查,在这里我们主要介绍空闲 http 连接的清理。对于连接池中的连接基本都是复用的,其中避免不了 server 端主动关闭连接,这个时候取出的连接自然是不可用的,当然可以通过上一篇文章中的可用性检查避免。但同时 httpclient 连接池也提供了 http 连接的清理策略,用来对连接进行清除。

http 连接的清理主要涉及了以下几个关键点:

  1. 如何开启连接清理

  2. 如何进行连接清理

如何开启连接清理

连接池中空闲连接的清理由 HttpClientBuilder 的 evictIdleConnections(ildleTime, timeUnit) 方法和 evictExpiredConnections() 方法进行设置。在进行 build 的时候根据上述设置开启清理,核心代码如下:

if (evictExpiredConnections || evictIdleConnections) {
    final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm, maxIdleTime > 0 ? maxIdleTime : 10, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS, maxIdleTime, maxIdleTimeUnit);
    closeablesCopy.add(new Closeable() {
                    @Override
                    public void close() throws IOException {
                        connectionEvictor.shutdown();
                        try {
                            connectionEvictor.awaitTermination(1L, TimeUnit.SECONDS);
                        } catch (final InterruptedException interrupted) {
                            Thread.currentThread().interrupt();
                        }
                    }
                });
   connectionEvictor.start();
}
  • 连接清理的核心类为 IdleConnectionEvictor 对象实例 ,本质是开启一个后台线程,默认不设置 evictIdleConnections(ildleTime, timeUnit) 方法的 ildleTime 的时候线程每 sleep 10秒钟进行清理一次,默认连接存活时间也为10秒。核心代码如下:

    public IdleConnectionEvictor(final HttpClientConnectionManager connectionManager, final ThreadFactory threadFactory, final long sleepTime, final TimeUnit sleepTimeUnit, final long maxIdleTime, final TimeUnit maxIdleTimeUnit) {
            this.connectionManager = Args.notNull(connectionManager, "Connection manager");
            this.threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory();
            this.sleepTimeMs = sleepTimeUnit != null ? sleepTimeUnit.toMillis(sleepTime) : sleepTime;
            this.maxIdleTimeMs = maxIdleTimeUnit != null ? maxIdleTimeUnit.toMillis(maxIdleTime) : maxIdleTime;
            this.thread = this.threadFactory.newThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (!Thread.currentThread().isInterrupted()) {
                            Thread.sleep(sleepTimeMs);
                            connectionManager.closeExpiredConnections();
                            if (maxIdleTimeMs > 0) {
                                connectionManager.closeIdleConnections(maxIdleTimeMs, TimeUnit.MILLISECONDS);
                            }
                        }
                    } catch (final Exception ex) {
                        exception = ex;
                    }
                }
            });
    }
    

如何进行连接清理

由上面 IdleConnectionEvictor 的代码可知,清理的核心是运行PoolingHttpClientConnectionManager 的 closeExpiredConnections()/closeIdleConnections() 这两个方法,而这两个方法本质是则是调用 Cpool 对象实例的 closeIdle() 方法和 closeExpired() 方法,核心代码如下:

public void closeIdle(final long idletime, final TimeUnit timeUnit) {
        Args.notNull(timeUnit, "Time unit");
        long time = timeUnit.toMillis(idletime);
        if (time < 0) {
            time = 0;
        }
        final long deadline = System.currentTimeMillis() - time;
        enumAvailable(new PoolEntryCallback<T, C>() {


            @Override
            public void process(final PoolEntry<T, C> entry) {
                if (entry.getUpdated() <= deadline) {
                    entry.close();
                }
            }


        });
    }


public void closeExpired() {
        final long now = System.currentTimeMillis();
        enumAvailable(new PoolEntryCallback<T, C>() {


            @Override
            public void process(final PoolEntry<T, C> entry) {
                if (entry.isExpired(now)) {
                    entry.close();
                }
            }


        });
 }


protected void enumAvailable(final PoolEntryCallback<T, C> callback) {
        this.lock.lock();
        try {
            final Iterator<E> it = this.available.iterator();
            while (it.hasNext()) {
                final E entry = it.next();
                callback.process(entry);
                if (entry.isClosed()) {
                    final RouteSpecificPool<T, C, E> pool = getPool(entry.getRoute());
                    pool.remove(entry);
                    it.remove();
                }
            }
            purgePoolMap();
        } finally {
            this.lock.unlock();
        }
 }
  • closeIdle() 方法是判断当前时间是否超过最新活跃时间+存活时间,这个存活时间由上面的 evictIdleConnections(ildleTime, timeUnit) 方法决定。

  • closeExpired() 方法是判断当前时间是否已经过期,这个过期时间根据以前文章,是由响应头 response header 的 Keep-Alive: timeout 的值决定。

  • 上面的操作对象均是针对以前文章中介绍的 global 池中可用连接集合 available。

  • 如果连接确实 Idel 或者 Expire,那么就会调用 CpoolEnrty 的 close() 方法,根据以前文章,这个方法本质上是关闭原始 socket 并且把内部 bind 的 socket 置为空。

  • 如果连接确实 Idel 或者 Expire ,那么同时也会把该连接从 global 池中可用连接集合 available 中移除,并且从以前文章介绍的 individual 池中的可用连接集合 available 中,以及正在使用连接集合 leased 中移除。这样确保在 global pool 和 individual pool 中均移除。

目前先写到这里,下一篇我们开始介绍 httpclient 连接池请求的 retry 和 ssl 的支持。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用HttpClient时,可以使用连接来提高性能和可靠性。连接可以管理多个HTTP连接,重用已经建立的连接,从而避免了每次请求都需要重新建立连接的开销。 以下是在Spring Boot中使用HttpClient连接的步骤: 1. 首先,需要在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> ``` 2. 接下来,在application.properties文件中配置HttpClient连接的参数,如下所示: ``` # HttpClient连接最大连接数 http.maxTotal=200 # HttpClient连接每个路由的最大连接数 http.maxPerRoute=20 # HttpClient连接连接超时时间 http.connectionTimeout=5000 # HttpClient连接请求超时时间 http.requestTimeout=5000 # HttpClient连接等待数据超时时间 http.socketTimeout=5000 ``` 3. 然后,在Spring Boot的配置类中创建HttpClient连接对象,并将其注入到需要使用的类中,如下所示: ``` @Configuration public class HttpClientConfig { @Value("${http.maxTotal}") private int maxTotal; @Value("${http.maxPerRoute}") private int maxPerRoute; @Value("${http.connectionTimeout}") private int connectionTimeout; @Value("${http.requestTimeout}") private int requestTimeout; @Value("${http.socketTimeout}") private int socketTimeout; @Bean public CloseableHttpClient httpClient() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxTotal); connectionManager.setDefaultMaxPerRoute(maxPerRoute); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(requestTimeout) .setSocketTimeout(socketTimeout) .build(); return HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .build(); } } ``` 4. 最后,在需要使用HttpClient的类中注入HttpClient对象,如下所示: ``` @Service public class MyService { @Autowired private CloseableHttpClient httpClient; public void doRequest() throws Exception { HttpGet httpGet = new HttpGet("http://www.example.com"); CloseableHttpResponse response = httpClient.execute(httpGet); // 处理响应 response.close(); } } ``` 这样,就可以使用HttpClient连接来管理HTTP连接,提高性能和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值