龙空技术网

OpenFeign实战之使用Http Client替换默认的Client

小小李liy 79

前言:

现在姐妹们对“httpclient怎么设置请求头”大体比较讲究,各位老铁们都需要分析一些“httpclient怎么设置请求头”的相关知识。那么小编也在网摘上收集了一些有关“httpclient怎么设置请求头””的相关知识,希望姐妹们能喜欢,小伙伴们快快来了解一下吧!

Feign默认是使用JDK原生的URLConnection发送HTTP请求,没有连接池,但是对每个地址会保持一个长连接,就是利用HTTP的persistence connection.。可以使用其他优秀的Client去替换,这样可以设置连接池,超时时间等对服务之间的调用调优。下面介绍使用Http Client和Okhttp替换Feign默认的Client。

使用Http Client替换默认的Client

pom.xml

<properties>    <maven.compiler.source>8</maven.compiler.source>    <maven.compiler.target>8</maven.compiler.target>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <spring.cloud-version>2021.0.5</spring.cloud-version></properties><parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>2.7.10</version></parent><dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-dependencies</artifactId>        <version>${spring.cloud-version}</version>        <type>pom</type>        <scope>import</scope>    </dependency>    <!-- Spring Cloud OpenFeign的Starter的依赖 -->    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-starter-openfeign</artifactId>        <version>3.1.5</version>    </dependency>    <!-- 使用Apache HttpClient替换Feign原生httpclient -->    <dependency>        <groupId>org.apache.httpcomponents</groupId>        <artifactId>httpclient</artifactId>    </dependency>    <dependency>        <groupId>io.github.openfeign</groupId>        <artifactId>feign-httpclient</artifactId>        <version>11.8</version>    </dependency>    <!-- Spring Boot Actuator的依赖 -->    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-actuator</artifactId>    </dependency>    <!-- 使用Gson库来处理JSON数据 -->    <dependency>        <groupId>io.github.openfeign</groupId>        <artifactId>feign-gson</artifactId>        <version>11.0</version>    </dependency>    <!-- 使用Fastjson库来处理JSON数据 -->    <dependency>        <groupId>com.alibaba</groupId>        <artifactId>fastjson</artifactId>        <version>1.2.62</version>    </dependency></dependencies>

application.yml

server:  port: 8090spring:  application:    name: openfeign-httpclientfeign:  httpclient:    enabled: true    #启用Http Client 替换默认的URLConnection

关于Http Client的一些配置也是可以在配置文件中配置的,在org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration中是关于HttpClient的配置:

@Configuration(    proxyBeanMethods = false)@ConditionalOnMissingBean({CloseableHttpClient.class})public class HttpClientFeignConfiguration {    private static final Log LOG = LogFactory.getLog(HttpClientFeignConfiguration.class);    private final Timer connectionManagerTimer = new Timer("FeignApacheHttpClientConfiguration.connectionManagerTimer", true);    private CloseableHttpClient httpClient;    @Autowired(        required = false    )    private RegistryBuilder registryBuilder;    public HttpClientFeignConfiguration() {    }    @Bean    @ConditionalOnMissingBean({HttpClientConnectionManager.class})    public HttpClientConnectionManager connectionManager(ApacheHttpClientConnectionManagerFactory connectionManagerFactory, FeignHttpClientProperties httpClientProperties) {        final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(), httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(), httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);        this.connectionManagerTimer.schedule(new TimerTask() {            public void run() {                connectionManager.closeExpiredConnections();            }        }, 30000L, (long)httpClientProperties.getConnectionTimerRepeat());        return connectionManager;    }    @Bean    @ConditionalOnProperty(        value = {"feign.compression.response.enabled"},        havingValue = "true"    )    public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {        HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties();        this.httpClient = this.createClient(builder, httpClientConnectionManager, httpClientProperties);        return this.httpClient;    }    @Bean    @ConditionalOnProperty(        value = {"feign.compression.response.enabled"},        havingValue = "false",        matchIfMissing = true    )    public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory, HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {        this.httpClient = this.createClient(httpClientFactory.createBuilder(), httpClientConnectionManager, httpClientProperties);        return this.httpClient;    }    private CloseableHttpClient createClient(HttpClientBuilder builder, HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(httpClientProperties.getConnectionTimeout()).setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();        CloseableHttpClient httpClient = builder.setDefaultRequestConfig(defaultRequestConfig).setConnectionManager(httpClientConnectionManager).build();        return httpClient;    }    @PreDestroy    public void destroy() {        this.connectionManagerTimer.cancel();        if (this.httpClient != null) {            try {                this.httpClient.close();            } catch (IOException var2) {                if (LOG.isErrorEnabled()) {                    LOG.error("Could not correctly close httpClient.");                }            }        }    }}

很明显当没有CloseableHttpClient这个bean的时候,就是会由这个类来生成Http Client的默认配置。所以说对于HttpClient的自定义配置可以通过自己注入CloseableHttpClient。还有HttpClientConnectionManager管理连接的bean。其实OpenFeign对HttpClient的支持很好,因为它的一些属性可以在配置文件中配置。

标签: #httpclient怎么设置请求头