Spring Cloud Feign Feign客户端组件配置

Feign 中默认使用 JDK 原生的 URLConnection 发送 HTTP 请求,我们可以集成别的组件来替换掉 URLConnection,比如 Apache HttpClient,OkHttp。

配置 OkHttp 只需要加入 OkHttp 的依赖,代码如下所示。

<dependency>
  <groupId>io.github.openfeigngroupId>
  <artifactId>feign-okhttpartifactId>
dependency>

然后修改配置,将 Feign 的 HttpClient 禁用,启用 OkHttp,配置如下:

#feign 使用 okhttp
feign.httpclient.enabled=false
feign.okhttp.enabled=true

关于配置可参考源码 org.springframework.cloud.openfeign.FeignAutoConfiguration
HttpClient 自动配置源码如下所示:

@Configuration
@ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
protected static class HttpClientFeignConfiguration {
     

    @Autowired(required = false)
    private HttpClient httpClient;

    @Bean
    @ConditionalOnMissingBean(Client.class)
    public Client feignClient() {
     
        if (this.httpClient != null) {
     
            return new ApacheHttpClient(this.httpClient);
        }
        return new ApacheHttpClient();
    }
}

OkHttp 自动配置源码如下所示:

@Configuration
@ConditionalOnClass(OkHttpClient.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnProperty(value = "feign.okhttp.enabled", matchIfMissing = true)
protected static class OkHttpFeignConfiguration {
     

    @Autowired(required = false)
    private okhttp3.OkHttpClient okHttpClient;

    @Bean
    @ConditionalOnMissingBean(Client.class)
    public Client feignClient() {
     
        if (this.okHttpClient != null) {
     
            return new OkHttpClient(this.okHttpClient);
        }
        return new OkHttpClient();
    }
}

上面所示两段代码分别是配置 HttpClient 和 OkHttp 的方法。其通过 @ConditionalOnProperty 中的值来决定启用哪种客户端(HttpClient 和 OkHttp),@ConditionalOnClass 表示对应的类在 classpath 目录下存在时,才会去解析对应的配置文件。

你可能感兴趣的:(《Spring,Cloud实战》,spring,cloud)