pom.xml
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>${version}</version>
</dependency>
yml
feign:
# feign启用hystrix,才能熔断、降级
# hystrix:
# enabled: true
# 启用 okhttp 关闭默认 httpclient
# httpclient:
# enabled: false #关闭httpclient
# 默认Feign使用的是JDK自带的URLConnection进行Http
okhttp:
enabled: true
# 请求与响应的压缩以提高通信效率
compression:
request:
enabled: true
min-request-size: 2048
mime-types: text/xml,application/xml,application/json
response:
enabled: true
config
/**
* 配置 okhttp 与连接池
* ConnectionPool 默认创建5个线程,保持5分钟长连接
*/
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class) //SpringBoot自动配置
public class OkHttpConfig {
// 默认老外留给你彩蛋中文乱码,加上它就 OK
@Bean
public Encoder encoder() {
return new FormEncoder();
}
@Bean
public okhttp3.OkHttpClient okHttpClient() {
return new okhttp3.OkHttpClient.Builder()
//设置连接超时
.connectTimeout(10, TimeUnit.SECONDS)
//设置读超时
.readTimeout(10, TimeUnit.SECONDS)
//设置写超时
.writeTimeout(10, TimeUnit.SECONDS)
//是否自动重连
.retryOnConnectionFailure(true)
//请求池
.connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES))
.build();
}
}
校验配置是否生效:
验证Apache HttpClient配置是否生效,通过debug调试,在feign.SynchronousMethodHandler#executeAndDecode()方法上打端断点,通过发起一个远程调用请求,在没配置替换前,是这样的:
配置替换后,可以看看默认使用的client是已经被替换成Apache HttpClient:
Spring Cloud OpenFeign远程调用性能优化