使用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连接管理的资料请关注脚本之家其它相关文章!

相关文章

  • springboot使用spring-data-jpa操作MySQL数据库

    springboot使用spring-data-jpa操作MySQL数据库

    这篇文章主要介绍了springboot使用spring-data-jpa操作MySQL数据库,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • 使用Java读取本地文件并转换为MultipartFile对象的方法

    使用Java读取本地文件并转换为MultipartFile对象的方法

    在许多Java Web应用中,我们经常会遇到将本地文件上传至服务器或其他系统的需求,在这种场景下,MultipartFile对象非常常用,用来表示HTTP请求中的文件,在本文中,我将演示如何编写代码来读取本地文件并将其转换为自定义的MultipartFile对象,需要的朋友可以参考下
    2025-08-08
  • spring如何实现依赖注入DI(spring-test方式)

    spring如何实现依赖注入DI(spring-test方式)

    本文主要介绍如何实现spring 的依赖注入,并且浅显的讲述一下注入需要注意的事项。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • java中response对象用法实例分析

    java中response对象用法实例分析

    这篇文章主要介绍了java中response对象用法,结合实例形式分析了Java中response对象的功能及具体使用技巧,需要的朋友可以参考下
    2015-12-12
  • Java实现高校教务系统

    Java实现高校教务系统

    这篇文章主要为大家详细介绍了Java实现高校教务系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • Maven引用自定义jar包方式

    Maven引用自定义jar包方式

    这篇文章主要介绍了Maven引用自定义jar包方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • spring整合atomikos实现分布式事务的方法示例

    spring整合atomikos实现分布式事务的方法示例

    本文整合了一个spring和atomikos的demo,并且通过案例演示说明atomikos的作用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-05-05
  • SpringBoot统一功能处理示例详解(拦截器)

    SpringBoot统一功能处理示例详解(拦截器)

    这篇文章主要介绍了SpringBoot统一功能处理(拦截器),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08
  • Java基础之文件概述

    Java基础之文件概述

    这篇文章主要介绍了Java基础之文件概述,文中有非常详细的代码示例,对正在学习java基础的小伙伴们有一定的帮助,需要的朋友可以参考下
    2021-05-05
  • JAVA JDK8 List分组的实现和用法

    JAVA JDK8 List分组的实现和用法

    今天小编就为大家分享一篇关于JAVA JDK8 List分组的实现和用法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12

最新评论