有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪" />

最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

HttpClient的KeepAlive接口方法源碼解析

 更新時間:2023年10月11日 08:45:41   作者:codecraft  
這篇文章主要為大家介紹了HttpClient的KeepAlive接口方法源碼解析,
有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

本文主要研究一下HttpClient的KeepAlive

ConnectionKeepAliveStrategy

org/apache/http/conn/ConnectionKeepAliveStrategy.java

public interface ConnectionKeepAliveStrategy {
    /**
     * Returns the duration of time which this connection can be safely kept
     * idle. If the connection is left idle for longer than this period of time,
     * it MUST not reused. A value of 0 or less may be returned to indicate that
     * there is no suitable suggestion.
     *
     * When coupled with a {@link org.apache.http.ConnectionReuseStrategy}, if
     * {@link org.apache.http.ConnectionReuseStrategy#keepAlive(
     *   HttpResponse, HttpContext)} returns true, this allows you to control
     * how long the reuse will last. If keepAlive returns false, this should
     * have no meaningful impact
     *
     * @param response
     *            The last response received over the connection.
     * @param context
     *            the context in which the connection is being used.
     *
     * @return the duration in ms for which it is safe to keep the connection
     *         idle, or <=0 if no suggested duration.
     */
    long getKeepAliveDuration(HttpResponse response, HttpContext context);
}
ConnectionKeepAliveStrategy接口定義了getKeepAliveDuration方法,用于返回該connection空間多久以內(nèi)被復用是安全的

DefaultConnectionKeepAliveStrategy

org/apache/http/impl/client/DefaultConnectionKeepAliveStrategy.java

@Contract(threading = ThreadingBehavior.IMMUTABLE)
public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
    public static final DefaultConnectionKeepAliveStrategy INSTANCE = new DefaultConnectionKeepAliveStrategy();
    @Override
    public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
        Args.notNull(response, "HTTP response");
        final HeaderElementIterator it = new BasicHeaderElementIterator(
                response.headerIterator(HTTP.CONN_KEEP_ALIVE));
        while (it.hasNext()) {
            final HeaderElement he = it.nextElement();
            final String param = he.getName();
            final String value = he.getValue();
            if (value != null && param.equalsIgnoreCase("timeout")) {
                try {
                    return Long.parseLong(value) * 1000;
                } catch(final NumberFormatException ignore) {
                }
            }
        }
        return -1;
    }
}
DefaultConnectionKeepAliveStrategy實現(xiàn)了ConnectionKeepAliveStrategy接口,它主要是從response的Keep-Alive的header讀取timeout參數(shù)

ConnectionReuseStrategy

org/apache/http/ConnectionReuseStrategy.java

public interface ConnectionReuseStrategy {
    /**
     * Decides whether a connection can be kept open after a request.
     * If this method returns {@code false}, the caller MUST
     * close the connection to correctly comply with the HTTP protocol.
     * If it returns {@code true}, the caller SHOULD attempt to
     * keep the connection open for reuse with another request.
     * <p>
     * One can use the HTTP context to retrieve additional objects that
     * may be relevant for the keep-alive strategy: the actual HTTP
     * connection, the original HTTP request, target host if known,
     * number of times the connection has been reused already and so on.
     * </p>
     * <p>
     * If the connection is already closed, {@code false} is returned.
     * The stale connection check MUST NOT be triggered by a
     * connection reuse strategy.
     * </p>
     *
     * @param response
     *          The last response received over that connection.
     * @param context   the context in which the connection is being
     *          used.
     *
     * @return {@code true} if the connection is allowed to be reused, or
     *         {@code false} if it MUST NOT be reused
     */
    boolean keepAlive(HttpResponse response, HttpContext context);
}
ConnectionReuseStrategy接口定義了keepAlive方法,用于判斷該connection是否保持連接繼續(xù)復用,還是直接關閉

DefaultClientConnectionReuseStrategy

org/apache/http/impl/client/DefaultClientConnectionReuseStrategy.java

public class DefaultClientConnectionReuseStrategy extends DefaultConnectionReuseStrategy {
    public static final DefaultClientConnectionReuseStrategy INSTANCE = new DefaultClientConnectionReuseStrategy();
    @Override
    public boolean keepAlive(final HttpResponse response, final HttpContext context) {
        final HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        if (request != null) {
            final Header[] connHeaders = request.getHeaders(HttpHeaders.CONNECTION);
            if (connHeaders.length != 0) {
                final TokenIterator ti = new BasicTokenIterator(new BasicHeaderIterator(connHeaders, null));
                while (ti.hasNext()) {
                    final String token = ti.nextToken();
                    if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
                        return false;
                    }
                }
            }
        }
        return super.keepAlive(response, context);
    }
}
DefaultClientConnectionReuseStrategy繼承了DefaultConnectionReuseStrategy,其keepAlive方法先判斷Connection這個header的值是不是Close,若是則返回false,其他邏輯復用父類的方法

MainClientExec

org/apache/http/impl/execchain/MainClientExec.java

@Override
    public CloseableHttpResponse execute(
            final HttpRoute route,
            final HttpRequestWrapper request,
            final HttpClientContext context,
            final HttpExecutionAware execAware) throws IOException, HttpException {
            //......
               response = requestExecutor.execute(request, managedConn, context);
                // The connection is in or can be brought to a re-usable state.
                if (reuseStrategy.keepAlive(response, context)) {
                    // Set the idle duration of this connection
                    final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                    if (this.log.isDebugEnabled()) {
                        final String s;
                        if (duration > 0) {
                            s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                        } else {
                            s = "indefinitely";
                        }
                        this.log.debug("Connection can be kept alive " + s);
                    }
                    connHolder.setValidFor(duration, TimeUnit.MILLISECONDS);
                    connHolder.markReusable();
                } else {
                    connHolder.markNonReusable();
                }
            //......
    }
MainClientExec的execute方法會通過reuseStrategy.keepAlive判斷連接是否可以復用,是的話則通過keepAliveStrategy.getKeepAliveDuration來獲取keepAlive時間,同時設置setValidFor(keepalive)及markReusable

releaseConnection

org/apache/http/impl/conn/PoolingHttpClientConnectionManager.java

@Override
    public void releaseConnection(
            final HttpClientConnection managedConn,
            final Object state,
            final long keepalive, final TimeUnit timeUnit) {
        Args.notNull(managedConn, "Managed connection");
        synchronized (managedConn) {
            final CPoolEntry entry = CPoolProxy.detach(managedConn);
            if (entry == null) {
                return;
            }
            final ManagedHttpClientConnection conn = entry.getConnection();
            try {
                if (conn.isOpen()) {
                    final TimeUnit effectiveUnit = timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS;
                    entry.setState(state);
                    entry.updateExpiry(keepalive, effectiveUnit);
                    if (this.log.isDebugEnabled()) {
                        final String s;
                        if (keepalive > 0) {
                            s = "for " + (double) effectiveUnit.toMillis(keepalive) / 1000 + " seconds";
                        } else {
                            s = "indefinitely";
                        }
                        this.log.debug("Connection " + format(entry) + " can be kept alive " + s);
                    }
                    conn.setSocketTimeout(0);
                }
            } finally {
                this.pool.release(entry, conn.isOpen() && entry.isRouteComplete());
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Connection released: " + format(entry) + formatStats(entry.getRoute()));
                }
            }
        }
    }
PoolingHttpClientConnectionManager的releaseConnection方法在連接是open的時候執(zhí)行entry.updateExpiry(keepalive, effectiveUnit)

PoolEntry

org/apache/http/pool/PoolEntry.java

public synchronized void updateExpiry(final long time, final TimeUnit timeUnit) {
        Args.notNull(timeUnit, "Time unit");
        this.updated = System.currentTimeMillis();
        final long newExpiry;
        if (time > 0) {
            newExpiry = this.updated + timeUnit.toMillis(time);
        } else {
            newExpiry = Long.MAX_VALUE;
        }
        this.expiry = Math.min(newExpiry, this.validityDeadline);
    }
    public synchronized boolean isExpired(final long now) {
        return now >= this.expiry;
    }
它在keepalive大于0的時候更新newExpiry為當前時間+keepalive時間,否則更新newExpiry為Long.MAX_VALUE,最后取newExpiry與validityDeadline的最小值作為entry的expiry;其isExpired方法用當前時間與expiry對比,大于等于的返回true

closeExpired

org/apache/http/pool/AbstractConnPool.java

/**
     * Closes expired connections and evicts them from the pool.
     */
    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();
                }
            }
        });
    }
closeExpired主要是遍歷available,挨個判斷是否expired,是則執(zhí)行close

小結

HttpClient的MainClientExec的execute方法會通過reuseStrategy.keepAlive判斷連接是否可以復用,是的話則通過keepAliveStrategy.getKeepAliveDuration來獲取keepAlive時間,同時設置setValidFor(keepalive)及markReusable;IdleConnectionEvictor線程每隔指定時間會執(zhí)行closeExpired方法,它是依據(jù)當前時間與entry的expiry時間進行比較得出,而expiry時間則取newExpiry與validityDeadline的最小值,其中newExpiry的時間取決于keepAliveStrategy.getKeepAliveDuration,而validityDeadline取決于connTimeToLive值。若connTimeToLive值沒有設置則默認為-1,那么validityDeadline的值是Long.MAX_VALUE,那么isExpired方法則取決于keepAliveStrategy.getKeepAliveDuration返回的值。若response的header沒有Keep-Alive或者Keep-Alive的header沒有timeout參數(shù)則keepAliveStrategy.getKeepAliveDuration返回-1(indefinitely),則newExpiry將是Long.MAX_VALUE。

默認keepalive是開啟的,如果走systemProperties,且http.keepAlive設置為false,則ConnectionReuseStrategy會被設置為NoConnectionReuseStrategy(keepAlive方法返回false),連接歸還的時候會被直接關閉。

doc Keep-Alive

以上就是HttpClient的KeepAlive接口方法源碼解析的詳細內(nèi)容,更多關于HttpClient KeepAlive接口的資料請關注腳本之家其它相關文章!

相關文章

最新評論

罗定市| 米易县| 兴义市| 江北区| 陇南市| 东阳市| 麻栗坡县| 辽宁省| 平罗县| 和政县| 西安市| 东源县| 全南县| 四平市| 莎车县| 马山县| 土默特右旗| 五河县| 偃师市| 新乡市| 桑植县| 仪陇县| 泗洪县| 襄汾县| 仲巴县| 永嘉县| 汉中市| 琼海市| 扶风县| 磐石市| 耒阳市| 闽侯县| 彭水| 元阳县| 蒙自县| 吴桥县| 龙陵县| 长治县| 兴化市| 大丰市| 开封县|