暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

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

TA码字 2020-03-31
1251
上一篇文章里我们介绍了 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 的支持。

        文章转载自TA码字,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

        评论