文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

SpringCloud Feign中怎么使用ApacheHttpClient代替默认client方式

2023-06-29 10:21

关注

这篇文章主要讲解了“SpringCloud Feign中怎么使用ApacheHttpClient代替默认client方式”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringCloud Feign中怎么使用ApacheHttpClient代替默认client方式”吧!

使用ApacheHttpClient代替默认client

ApacheHttpClient和默认实现的比较

ApacheHttpClient 使用

maven 依赖

    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-starter-openfeign</artifactId>    </dependency>    <dependency>        <groupId>org.apache.httpcomponents</groupId>        <artifactId>httpclient</artifactId>        <version>4.5.7</version>    </dependency>    <dependency>        <groupId>io.github.openfeign</groupId>        <artifactId>feign-httpclient</artifactId>        <version>10.1.0</version>    </dependency>

配置文件的修改

feign:  httpclient:    enabled: true

创建ApacheHttpClient客户端
 

import javax.net.ssl.SSLContext;import lombok.extern.slf4j.Slf4j;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.springframework.util.ResourceUtils;import feign.httpclient.ApacheHttpClient;@Slf4jpublic class FeignClientBuilder {  private boolean enabled;  private String keyPassword;  private String keyStore;  private String keyStorePassword;  private String trustStore;  private String trustStorePassword;  private int maxConnTotal = 2048;  private int maxConnPerRoute = 512;  public FeignClientBuilder(boolean enabled, String keyPassword, String keyStore, String keyStorePassword, String trustStore, String trustStorePassword, int maxConnTotal, int maxConnPerRoute) {    this.enabled = enabled;    this.keyPassword = keyPassword;    this.keyStore = keyStore;    this.keyStorePassword = keyStorePassword;    this.trustStore = trustStore;    this.trustStorePassword = trustStorePassword;        this.maxConnTotal = maxConnTotal;        this.maxConnPerRoute = maxConnPerRoute;  }  public ApacheHttpClient apacheHttpClient() {    CloseableHttpClient defaultHttpClient = HttpClients.custom()            .setMaxConnTotal(maxConnTotal)            .setMaxConnPerRoute(maxConnPerRoute)            .build();    ApacheHttpClient defaultApacheHttpClient = new ApacheHttpClient(defaultHttpClient);    if (!enabled) {      return defaultApacheHttpClient;    }    SSLContextBuilder sslContextBuilder = SSLContexts.custom();    // 如果 服务端启用了 TLS 客户端验证,则需要指定 keyStore    if (keyStore == null || keyStore.isEmpty()) {      return new ApacheHttpClient();    } else {      try {        sslContextBuilder                .loadKeyMaterial(                        ResourceUtils.getFile(keyStore),                        keyStorePassword.toCharArray(),                        keyPassword.toCharArray());      } catch (Exception e) {        e.printStackTrace();      }    }    // 如果 https 使用自签名证书,则需要指定 trustStore    if (trustStore == null || trustStore.isEmpty()) {    } else {      try {        sslContextBuilder//        .loadTrustMaterial(TrustAllStrategy.INSTANCE)                .loadTrustMaterial(                        ResourceUtils.getFile(trustStore),                        trustStorePassword.toCharArray()                );      } catch (Exception e) {        e.printStackTrace();      }    }    try {      SSLContext sslContext = sslContextBuilder.build();      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(              sslContext,              SSLConnectionSocketFactory.getDefaultHostnameVerifier());      CloseableHttpClient httpClient = HttpClients.custom()              .setMaxConnTotal(maxConnTotal)              .setMaxConnPerRoute(maxConnPerRoute)              .setSSLSocketFactory(sslsf)              .build();      ApacheHttpClient apacheHttpClient = new ApacheHttpClient(httpClient);      log.info("feign Client load with ssl.");      return apacheHttpClient;    } catch (Exception e) {      e.printStackTrace();    }    return defaultApacheHttpClient;  }  public static FeignClientBuilderBuilder builder() {    return new FeignClientBuilderBuilder();  }  public static class FeignClientBuilderBuilder {    private boolean enabled;    private String keyPassword;    private String keyStore;    private String keyStorePassword;    private String trustStore;    private String trustStorePassword;    private int maxConnTotal = 2048;    private int maxConnPerRoute = 512;    public FeignClientBuilderBuilder enabled(boolean enabled) {      this.enabled = enabled;      return this;    }    public FeignClientBuilderBuilder keyPassword(String keyPassword) {      this.keyPassword = keyPassword;      return this;    }    public FeignClientBuilderBuilder keyStore(String keyStore) {      this.keyStore = keyStore;      return this;    }    public FeignClientBuilderBuilder keyStorePassword(String keyStorePassword) {      this.keyStorePassword = keyStorePassword;      return this;    }    public FeignClientBuilderBuilder trustStore(String trustStore) {      this.trustStore = trustStore;      return this;    }    public FeignClientBuilderBuilder trustStorePassword(String trustStorePassword) {      this.trustStorePassword = trustStorePassword;      return this;    }    public FeignClientBuilderBuilder maxConnTotal(int maxConnTotal) {      this.maxConnTotal = maxConnTotal;      return this;    }    public FeignClientBuilderBuilder maxConnPerRoute(int maxConnPerRoute) {      this.maxConnPerRoute = maxConnPerRoute;      return this;    }    public FeignClientBuilder build() {      return new FeignClientBuilder(              this.enabled,              this.keyPassword,              this.keyStore,              this.keyStorePassword,              this.trustStore,              this.trustStorePassword,              this.maxConnTotal,              this.maxConnPerRoute      );    }  }}


使用时可以直接使用builder来创建ApacheHttpClient。
 

apache的HttpClient的默认重试机制

maven

        <dependency>            <groupId>org.apache.httpcomponents</groupId>            <artifactId>httpclient</artifactId>            <version>4.5.2</version>        </dependency>

异常重试log

2017-01-31 19:31:39.057  INFO 3873 --- [askScheduler-13] o.apache.http.impl.execchain.RetryExec   : I/O exception (org.apache.http.NoHttpResponseException) caught when processing request to {}->http://192.168.99.100:8080: The target server failed to respond
2017-01-31 19:31:39.058  INFO 3873 --- [askScheduler-13] o.apache.http.impl.execchain.RetryExec   : Retrying request to {}->http://192.168.99.100:8080

RetryExec

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

@Immutablepublic class RetryExec implements ClientExecChain {    private final Log log = LogFactory.getLog(getClass());    private final ClientExecChain requestExecutor;    private final HttpRequestRetryHandler retryHandler;    public RetryExec(            final ClientExecChain requestExecutor,            final HttpRequestRetryHandler retryHandler) {        Args.notNull(requestExecutor, "HTTP request executor");        Args.notNull(retryHandler, "HTTP request retry handler");        this.requestExecutor = requestExecutor;        this.retryHandler = retryHandler;    }    @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");        final Header[] origheaders = request.getAllHeaders();        for (int execCount = 1;; execCount++) {            try {                return this.requestExecutor.execute(route, request, context, execAware);            } catch (final IOException ex) {                if (execAware != null && execAware.isAborted()) {                    this.log.debug("Request has been aborted");                    throw ex;                }                if (retryHandler.retryRequest(ex, execCount, context)) {                    if (this.log.isInfoEnabled()) {                        this.log.info("I/O exception ("+ ex.getClass().getName() +                                ") caught when processing request to "                                + route +                                ": "                                + ex.getMessage());                    }                    if (this.log.isDebugEnabled()) {                        this.log.debug(ex.getMessage(), ex);                    }                    if (!RequestEntityProxy.isRepeatable(request)) {                        this.log.debug("Cannot retry non-repeatable request");                        throw new NonRepeatableRequestException("Cannot retry request " +                                "with a non-repeatable request entity", ex);                    }                    request.setHeaders(origheaders);                    if (this.log.isInfoEnabled()) {                        this.log.info("Retrying request to " + route);                    }                } else {                    if (ex instanceof NoHttpResponseException) {                        final NoHttpResponseException updatedex = new NoHttpResponseException(                                route.getTargetHost().toHostString() + " failed to respond");                        updatedex.setStackTrace(ex.getStackTrace());                        throw updatedex;                    } else {                        throw ex;                    }                }            }        }    }}

DefaultHttpRequestRetryHandler

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

@Immutablepublic class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler {    public static final DefaultHttpRequestRetryHandler INSTANCE = new DefaultHttpRequestRetryHandler();        private final int retryCount;        private final boolean requestSentRetryEnabled;    private final Set<Class<? extends IOException>> nonRetriableClasses;        protected DefaultHttpRequestRetryHandler(            final int retryCount,            final boolean requestSentRetryEnabled,            final Collection<Class<? extends IOException>> clazzes) {        super();        this.retryCount = retryCount;        this.requestSentRetryEnabled = requestSentRetryEnabled;        this.nonRetriableClasses = new HashSet<Class<? extends IOException>>();        for (final Class<? extends IOException> clazz: clazzes) {            this.nonRetriableClasses.add(clazz);        }    }        @SuppressWarnings("unchecked")    public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) {        this(retryCount, requestSentRetryEnabled, Arrays.asList(                InterruptedIOException.class,                UnknownHostException.class,                ConnectException.class,                SSLException.class));    }        public DefaultHttpRequestRetryHandler() {        this(3, false);    }        @Override    public boolean retryRequest(            final IOException exception,            final int executionCount,            final HttpContext context) {        Args.notNull(exception, "Exception parameter");        Args.notNull(context, "HTTP context");        if (executionCount > this.retryCount) {            // Do not retry if over max retry count            return false;        }        if (this.nonRetriableClasses.contains(exception.getClass())) {            return false;        } else {            for (final Class<? extends IOException> rejectException : this.nonRetriableClasses) {                if (rejectException.isInstance(exception)) {                    return false;                }            }        }        final HttpClientContext clientContext = HttpClientContext.adapt(context);        final HttpRequest request = clientContext.getRequest();        if(requestIsAborted(request)){            return false;        }        if (handleAsIdempotent(request)) {            // Retry if the request is considered idempotent            return true;        }        if (!clientContext.isRequestSent() || this.requestSentRetryEnabled) {            // Retry if the request has not been sent fully or            // if it's OK to retry methods that have been sent            return true;        }        // otherwise do not retry        return false;    }        public boolean isRequestSentRetryEnabled() {        return requestSentRetryEnabled;    }        public int getRetryCount() {        return retryCount;    }        protected boolean handleAsIdempotent(final HttpRequest request) {        return !(request instanceof HttpEntityEnclosingRequest);    }        @Deprecated    protected boolean requestIsAborted(final HttpRequest request) {        HttpRequest req = request;        if (request instanceof RequestWrapper) { // does not forward request to original            req = ((RequestWrapper) request).getOriginal();        }        return (req instanceof HttpUriRequest && ((HttpUriRequest)req).isAborted());    }}

默认重试3次,三次都失败则抛出NoHttpResponseException或其他异常

感谢各位的阅读,以上就是“SpringCloud Feign中怎么使用ApacheHttpClient代替默认client方式”的内容了,经过本文的学习后,相信大家对SpringCloud Feign中怎么使用ApacheHttpClient代替默认client方式这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯