使用Backoff策略提高HttpClient连接管理的效率

 更新时间:2023年10月15日 09:04:41   作者:codecraft  
这篇文章主要为大家介绍了Backoff策略提高HttpClient连接管理的效率使用解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下HttpClient的ConnectionBackoffStrategy

ConnectionBackoffStrategy

org/apache/http/client/ConnectionBackoffStrategy.java

/**
 * When managing a dynamic number of connections for a given route, this
 * strategy assesses whether a given request execution outcome should
 * result in a backoff signal or not, based on either examining the
 * {@code Throwable} that resulted or by examining the resulting
 * response (e.g. for its status code).
 *
 * @since 4.2
 *
 */
public interface ConnectionBackoffStrategy {

    /**
     * Determines whether seeing the given {@code Throwable} as
     * a result of request execution should result in a backoff
     * signal.
     * @param t the {@code Throwable} that happened
     * @return {@code true} if a backoff signal should be
     *   given
     */
    boolean shouldBackoff(Throwable t);

    /**
     * Determines whether receiving the given {@link HttpResponse} as
     * a result of request execution should result in a backoff
     * signal. Implementations MUST restrict themselves to examining
     * the response header and MUST NOT consume any of the response
     * body, if any.
     * @param resp the {@code HttpResponse} that was received
     * @return {@code true} if a backoff signal should be
     *   given
     */
    boolean shouldBackoff(HttpResponse resp);
}
ConnectionBackoffStrategy定义了shouldBackoff方法,它根据异常或者response来进行判断

NullBackoffStrategy

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

public class NullBackoffStrategy implements ConnectionBackoffStrategy {

    @Override
    public boolean shouldBackoff(final Throwable t) {
        return false;
    }

    @Override
    public boolean shouldBackoff(final HttpResponse resp) {
        return false;
    }
}
NullBackoffStrategy实现了ConnectionBackoffStrategy,shouldBackoff方法返回false

DefaultBackoffStrategy

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

public class DefaultBackoffStrategy implements ConnectionBackoffStrategy {

    @Override
    public boolean shouldBackoff(final Throwable t) {
        return t instanceof SocketTimeoutException || t instanceof ConnectException;
    }

    @Override
    public boolean shouldBackoff(final HttpResponse resp) {
        return resp.getStatusLine().getStatusCode() == 429 ||
            resp.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE;
    }

}
DefaultBackoffStrategy在SocketTimeoutException或者ConnectException的时候返回true,或者在response code为429或者503的时候返回true

BackoffStrategyExec

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

@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL)
public class BackoffStrategyExec implements ClientExecChain {
    private final ClientExecChain requestExecutor;
    private final ConnectionBackoffStrategy connectionBackoffStrategy;
    private final BackoffManager backoffManager;
    public BackoffStrategyExec(
            final ClientExecChain requestExecutor,
            final ConnectionBackoffStrategy connectionBackoffStrategy,
            final BackoffManager backoffManager) {
        super();
        Args.notNull(requestExecutor, "HTTP client request executor");
        Args.notNull(connectionBackoffStrategy, "Connection backoff strategy");
        Args.notNull(backoffManager, "Backoff manager");
        this.requestExecutor = requestExecutor;
        this.connectionBackoffStrategy = connectionBackoffStrategy;
        this.backoffManager = backoffManager;
    }
    @Override
    public CloseableHttpResponse execute(
            final HttpRoute route,
            final HttpRequestWrapper request,
            final HttpClientContext context,
            final HttpExecutionAware execAware) throws IOException, HttpException {
        Args.notNull(route, "HTTP route");
        Args.notNull(request, "HTTP request");
        Args.notNull(context, "HTTP context");
        CloseableHttpResponse out = null;
        try {
            out = this.requestExecutor.execute(route, request, context, execAware);
        } catch (final Exception ex) {
            if (out != null) {
                out.close();
            }
            if (this.connectionBackoffStrategy.shouldBackoff(ex)) {
                this.backoffManager.backOff(route);
            }
            if (ex instanceof RuntimeException) {
                throw (RuntimeException) ex;
            }
            if (ex instanceof HttpException) {
                throw (HttpException) ex;
            }
            if (ex instanceof IOException) {
                throw (IOException) ex;
            }
            throw new UndeclaredThrowableException(ex);
        }
        if (this.connectionBackoffStrategy.shouldBackoff(out)) {
            this.backoffManager.backOff(route);
        } else {
            this.backoffManager.probe(route);
        }
        return out;
    }
}

BackoffStrategyExec实现了ClientExecChain接口,其execute执行requestExecutor.execute,捕获到异常的时候通过connectionBackoffStrategy.shouldBackoff(ex)来决定是否需要backOff,是的话执行backoffManager.backOff(route);

若没有异常则通过connectionBackoffStrategy.shouldBackoff(out)根据response来判断是否需要backOff,是的化执行backoffManager.backOff(route)

小结

HttpClient的DefaultBackoffStrategy在SocketTimeoutException或者ConnectException的时候返回true,或者在response code为429或者503的时候返回true;BackoffStrategyExec则通过connectionBackoffStrategy与backoffManager来配合执行backOff。这个backOff的目的就是动态调整每个route的connection大小(MaxPerRoute)。

以上就是使用Backoff策略提高HttpClient连接管理的效率的详细内容,更多关于HttpClient Backoff连接管理的资料请关注脚本之家其它相关文章!

相关文章

  • spring boot国际化之MessageSource的使用方法

    spring boot国际化之MessageSource的使用方法

    这篇文章主要给大家介绍了spring boot国际化之MessageSource使用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Mybatis两种不同批量插入方式的区别

    Mybatis两种不同批量插入方式的区别

    随着业务需要,有时我们需要将数据批量添加到数据库,mybatis提供了将list集合循环添加到数据库的方法,这篇文章主要给大家介绍了关于Mybatis两种不同批量插入方式的区别,需要的朋友可以参考下
    2021-09-09
  • Redis 集成Spring的示例代码(spring-data-redis)

    Redis 集成Spring的示例代码(spring-data-redis)

    本篇文章主要介绍了Redis 集成Spring的示例代码(spring-data-redis) ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-09-09
  • Java String类常用方法梳理总结

    Java String类常用方法梳理总结

    这篇文章主要介绍了Java String类常用方法梳理总结,类 String 中包括用于检查各个字符串的方法,比如用于比较字符串,搜索字符串,更多相关内容需要的朋友可以参考一下
    2022-06-06
  • Java多线程知识点全面总结

    Java多线程知识点全面总结

    这篇文章主要介绍了Java多线程知识点全面总结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • Spring Boot整合swagger使用教程详解

    Spring Boot整合swagger使用教程详解

    这篇文章主要介绍了Spring Boot整合swagger使用教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • SpringBoot详解如果通过@Value注解给静态变量注入值

    SpringBoot详解如果通过@Value注解给静态变量注入值

    这篇文章主要介绍了springboot如何通过@Value给静态变量注入值,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • Windows下使用IDEA搭建Hadoop开发环境的详细方法

    Windows下使用IDEA搭建Hadoop开发环境的详细方法

    这篇文章主要介绍了Windows下使用IDEA搭建Hadoop开发环境,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Java如何通过jstack命令查询日志

    Java如何通过jstack命令查询日志

    在分析线上问题时常使用到jstack <PID>命令将当时Java应用程序的线程堆栈dump出来,面对jstack 日志,我们如何查看?下面小编给大家介绍下Java如何通过jstack命令查询日志,感兴趣的朋友一起看看吧
    2023-03-03
  • 详解SpringBoot如何实现统一后端返回格式

    详解SpringBoot如何实现统一后端返回格式

    在前后端分离的项目中后端返回的格式一定要友好,不然会对前端的开发人员带来很多的工作量。那么SpringBoot如何做到统一的后端返回格式呢?本文将为大家详细讲讲
    2022-04-04

最新评论