聊聊HttpClient的BackoffManager

本文主要研究一下HttpClient的BackoffManager

BackoffManager

org/apache/http/client/BackoffManager.java

复制代码
/**
 * Represents a controller that dynamically adjusts the size
 * of an available connection pool based on feedback from
 * using the connections.
 *
 * @since 4.2
 *
 */
public interface BackoffManager {

    /**
     * Called when we have decided that the result of
     * using a connection should be interpreted as a
     * backoff signal.
     */
    public void backOff(HttpRoute route);

    /**
     * Called when we have determined that the result of
     * using a connection has succeeded and that we may
     * probe for more connections.
     */
    public void probe(HttpRoute route);
}

BackoffManager接口主要用于根据connection的情况来动态调整连接池的connection大小,它定义了backOff方法用于缩小连接数,probe方法用于扩大连接数

AIMDBackoffManager

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

复制代码
/**
 * <p>The {@code AIMDBackoffManager} applies an additive increase,
 * multiplicative decrease (AIMD) to managing a dynamic limit to
 * the number of connections allowed to a given host. You may want
 * to experiment with the settings for the cooldown periods and the
 * backoff factor to get the adaptive behavior you want.</p>
 *
 * <p>Generally speaking, shorter cooldowns will lead to more steady-state
 * variability but faster reaction times, while longer cooldowns
 * will lead to more stable equilibrium behavior but slower reaction
 * times.</p>
 *
 * <p>Similarly, higher backoff factors promote greater
 * utilization of available capacity at the expense of fairness
 * among clients. Lower backoff factors allow equal distribution of
 * capacity among clients (fairness) to happen faster, at the
 * expense of having more server capacity unused in the short term.</p>
 *
 * @since 4.2
 */
public class AIMDBackoffManager implements BackoffManager {

    private final ConnPoolControl<HttpRoute> connPerRoute;
    private final Clock clock;
    private final Map<HttpRoute,Long> lastRouteProbes;
    private final Map<HttpRoute,Long> lastRouteBackoffs;
    private long coolDown = 5 * 1000L;
    private double backoffFactor = 0.5;
    private int cap = 2; // Per RFC 2616 sec 8.1.4

    /**
     * Creates an {@code AIMDBackoffManager} to manage
     * per-host connection pool sizes represented by the
     * given {@link ConnPoolControl}.
     * @param connPerRoute per-host routing maximums to
     *   be managed
     */
    public AIMDBackoffManager(final ConnPoolControl<HttpRoute> connPerRoute) {
        this(connPerRoute, new SystemClock());
    }

    AIMDBackoffManager(final ConnPoolControl<HttpRoute> connPerRoute, final Clock clock) {
        this.clock = clock;
        this.connPerRoute = connPerRoute;
        this.lastRouteProbes = new HashMap<HttpRoute,Long>();
        this.lastRouteBackoffs = new HashMap<HttpRoute,Long>();
    }

    @Override
    public void backOff(final HttpRoute route) {
        synchronized(connPerRoute) {
            final int curr = connPerRoute.getMaxPerRoute(route);
            final Long lastUpdate = getLastUpdate(lastRouteBackoffs, route);
            final long now = clock.getCurrentTime();
            if (now - lastUpdate.longValue() < coolDown) {
                return;
            }
            connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr));
            lastRouteBackoffs.put(route, Long.valueOf(now));
        }
    }

    private int getBackedOffPoolSize(final int curr) {
        if (curr <= 1) {
            return 1;
        }
        return (int)(Math.floor(backoffFactor * curr));
    }

    @Override
    public void probe(final HttpRoute route) {
        synchronized(connPerRoute) {
            final int curr = connPerRoute.getMaxPerRoute(route);
            final int max = (curr >= cap) ? cap : curr + 1;
            final Long lastProbe = getLastUpdate(lastRouteProbes, route);
            final Long lastBackoff = getLastUpdate(lastRouteBackoffs, route);
            final long now = clock.getCurrentTime();
            if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown) {
                return;
            }
            connPerRoute.setMaxPerRoute(route, max);
            lastRouteProbes.put(route, Long.valueOf(now));
        }
    }

    private Long getLastUpdate(final Map<HttpRoute,Long> updates, final HttpRoute route) {
        Long lastUpdate = updates.get(route);
        if (lastUpdate == null) {
            lastUpdate = Long.valueOf(0L);
        }
        return lastUpdate;
    }

    /**
     * Sets the factor to use when backing off; the new
     * per-host limit will be roughly the current max times
     * this factor. {@code Math.floor} is applied in the
     * case of non-integer outcomes to ensure we actually
     * decrease the pool size. Pool sizes are never decreased
     * below 1, however. Defaults to 0.5.
     * @param d must be between 0.0 and 1.0, exclusive.
     */
    public void setBackoffFactor(final double d) {
        Args.check(d > 0.0 && d < 1.0, "Backoff factor must be 0.0 < f < 1.0");
        backoffFactor = d;
    }

    /**
     * Sets the amount of time, in milliseconds, to wait between
     * adjustments in pool sizes for a given host, to allow
     * enough time for the adjustments to take effect. Defaults
     * to 5000L (5 seconds).
     * @param l must be positive
     */
    public void setCooldownMillis(final long l) {
        Args.positive(coolDown, "Cool down");
        coolDown = l;
    }

    /**
     * Sets the absolute maximum per-host connection pool size to
     * probe up to; defaults to 2 (the default per-host max).
     * @param cap must be &gt;= 1
     */
    public void setPerHostConnectionCap(final int cap) {
        Args.positive(cap, "Per host connection cap");
        this.cap = cap;
    }

}

AIMD即Additive Increase Multiplicative Decrease的缩写(线性增长,指数回退),TCP拥塞控制用的就是这种算法。线性增长就是在没有异常的场景下进行增长,遇到异常时执行指数回退。
AIMDBackoffManager实现了BackoffManager接口,它维护了lastRouteBackoffs、lastRouteProbes,backOff的时候通过lastRouteBackoffs获取最近backOff的时间,然后判断时间差是否小于coolDown时间,若小于则不操作,否则更新maxPerRoute为getBackedOffPoolSize(Math.floor(backoffFactor * curr))
probe方法先获取最近probe及backOff的时间,若最近probe/backOff与当前时间差小于coolDown则不处理,否则更新maxPerRoute为(curr >= cap) ? cap : curr + 1,默认cap为2,还不能修改,这个配置已经过时了,应该把cap设置为用户最初设定的maxPerRoute

小结

HttpClient的BackoffManager接口主要用于根据connection的情况来动态调整连接池的connection大小,它定义了backOff方法用于缩小连接数,probe方法用于扩大连接数。其默认采用与TCP拥塞控制相同的AIMD算法,异常时缩小为backoffFactor * curr,成功时扩大为(curr >= cap) ? cap : curr + 1,默认cap为2,还不能修改,这个配置已经过时了,应该把cap设置为用户最初设定的maxPerRoute。

相关推荐
斑马13915 分钟前
Linux软件编程学习笔记(十二)——TCP并发服务器模型
java·服务器·网络
冬栈程序设计19 分钟前
Springboot宿舍管理系统【670099】 -附源码(开箱即用)
java·毕业设计·springboot·课程设计·程序设计·大作业
2601_9622845027 分钟前
北京Java全栈开发培训 Web前端开发 软件测试就业培训班
java·软件测试·web前端·全栈开发·就业培训
ControlRookie43 分钟前
第22篇_源码加更 04|chunked 解码器和十六进制块长度解析
http·codesys·plc通信·开源源码
qiaosaifei1 小时前
JAVA老项目中有大量的类名_编译时报找不到符号错误
java·开发语言
聪明蛋子哟1 小时前
MCP协议深度落地:如何用Python/Java双语言实现统一的工具调用网关?
java·开发语言·python
文子越来越强1 小时前
【双因子认证】拦截注解@MFACheck 接入指南(其他微服务如何用)
java
ZGG0031 小时前
线程池详解:从 7 大参数到生产避坑
java·数据库·后端
迪康Defender2 小时前
公用电脑责任追溯难?迪康端点安全一体化管理系统用户模式详解
java·运维·开发语言·网络·其他·安全
京师20万禁军教头2 小时前
47-常用类-八大包装类(Wrapper Classes)
java