Spring Cloud Feign的自定义配置及使用
Feign 提供了很多的扩展机制,让用户可以更加灵活的使用。
# 1、日志配置
有时候我们遇到 Bug,比如接口调用失败、参数没收到等问题,或者想看看调用性能,就需要配置 Feign 的日志了,以此让 Feign 把请求信息输出来。
- 定义一个配置类,指定日志级别
// 注意:加上 @Configuration 会全局生效;
// 如果想让日志配置只对某个微服务生效,配置类不要加 @Configuration 注解
public class FeignConfig {
/**
* 配置 Feign 日志级别
* @return FULL 日志级别(开发环境推荐)
*/
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
通过源码可以看到日志等级有 4 种,分别是:
| 日志级别 | 含义 | 使用建议 |
|---|---|---|
| NONE | 不记录任何日志(默认) | 性能最佳,适用于生产环境 |
| BASIC | 记录请求方法、URL、响应状态码、执行时间 | 适用于生产环境问题追踪 |
| HEADERS | 在 BASIC 基础上,记录请求和响应的 header | 调试请求头信息时使用 |
| FULL | 记录请求和响应的所有内容,包括 header、body 和元数据 | 开发和测试环境推荐 |
- 局部配置,让调用的微服务生效,在@FeignClient 注解中指定使用的配置类
指定服务生效: 在 @FeignClient 注解中通过 configuration 属性指定:
@FeignClient(name = "order-service", configuration = FeignConfig.class)
public interface OrderClient {
// ...
}

- 在yml配置文件中执行 Client 的日志级别才能正常输出日志,格式是"logging.level.feign接口包路径=debug"
logging:
level:
com.tuling.mall.feigndemo.feign: debug
测试:BASIC级别日志

补充:局部配置可以在yml中配置
对应属性配置类: org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration
feign:
client:
config:
mall-order: # 指定微服务名
loggerLevel: FULL
# 2、契约配置
Spring Cloud 在 Feign 的基础上做了扩展,使用 Spring MVC 的注解来完成Feign的功能。原生的 Feign 是不支持 Spring MVC 注解的,如果你想在 Spring Cloud 中使用原生的注解方式来定义客户端也是可以的,通过配置契约来改变这个配置,Spring Cloud 中默认的是 SpringMvcContract。
Spring Cloud 1 早期版本就是用的原生Fegin. 随着netflix的停更替换成了Open feign
- 支持 Feign 原生注解,如 @RequestLine, @Param 等。
@Bean
public Contract feignContract() {
return new Contract.Default();
}
⚠️ 注意:启用后 不再支持 SpringMVC 注解,需使用 Feign 原生注解。
- OrderFeignService 中配置使用Feign原生的注解
@FeignClient(value = "mall-order", path = "/order")
public interface OrderFeignService {
@RequestLine("GET /findOrderByUserId/{userId}")
R findOrderByUserId(@Param("userId") Integer userId);
}
- 补充,也可以通过yml配置契约
feign:
client:
config:
mall-order:
loggerLevel: FULL
contract: feign.Contract.Default
# 3、自定义拦截器实现认证逻辑
public class FeignAuthRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
// 业务逻辑
String accessToken = UUID.randomUUID().toString();
template.header("Authorization", accessToken);
}
}
// 全局配置
@Configuration
public class FeignConfig {
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
@Bean // 自定义拦截器
public FeignAuthRequestInterceptor feignAuthRequestInterceptor() {
return new FeignAuthRequestInterceptor();
}
}
测试

补充:可以在yml中配置
feign:
client:
config:
mall-order:
requestInterceptors[0]: com.tuling.mall.feigndemo.interceptor.FeignAuthRequestInterceptor
mall-order端可以通过 @RequestHeader获取请求参数
建议在filter,interceptor中处理
# 4、超时时间配置
通过 Options 可以配置连接超时时间和读取超时时间,Options 的第一个参数是连接的超时时间(ms),默认值是 2s;第二个是请求处理的超时时间(ms),默认值是 5s。
# 全局配置
@Configuration
public class FeignConfig {
@Bean
public Request.Options options() {
return new Request.Options(5000, 10000); // 连接5秒,请求10秒
}
}
# yml中配置
feign:
client:
config:
mall-order:
connectTimeout: 5000 # 默认2000ms
readTimeout: 10000 # 默认5000ms
补充说明: Feign的底层用的是Ribbon,但超时时间以Feign配置为准
测试超时情况:

返回结果

# 5、客户端组件配置
Feign 中默认使用 JDK 原生的 URLConnection 发送 HTTP 请求,我们可以集成别的组件来替换掉 URLConnection,比如 Apache HttpClient,OkHttp。
Feign发起调用真正执行逻辑:feign.Client#execute (扩展点)

# 5.1、配置Apache HttpClient
引入依赖
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
<!-- Feign 集成 Apache HttpClient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.1.0</version>
</dependency>
然后修改yml配置,将 Feign 的 Apache HttpClient启用 :
feign:
# feign 使用 Apache HttpClient 可以忽略,默认开启
httpclient:
enabled: true
关于配置可参考源码: org.springframework.cloud.openfeign.FeignAutoConfiguration

测试:调用会进入feign.httpclient.ApacheHttpClient#execute
# 5.2、配置 OkHttp
引入依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
然后修改yml配置,将 Feign 的 HttpClient 禁用,启用 OkHttp,配置如下:
feign:
# 禁用默认 HttpClient
httpclient:
enabled: false
# 启用 OkHttp 作为底层客户端
okhttp:
enabled: true
关于配置可参考源码: org.springframework.cloud.openfeign.FeignAutoConfiguration

测试:调用会进入feign.okhttp.OkHttpClient#execute
# 6、GZIP 压缩配置
开启压缩可以有效节约网络资源,提升接口性能,我们可以配置 GZIP 来压缩数据:
feign:
# 配置 GZIP 来压缩数据
compression:
request:
enabled: true # 开启请求压缩
mime-types: text/xml,application/xml,application/json # 支持的压缩类型
min-request-size: 2048 # 最小压缩请求体积(字节)
response:
enabled: true # 开启响应压缩
注意:只有当 Feign 的 Http Client 不是 okhttp3 的时候,压缩才会生效,配置源码在 FeignAcceptGzipEncodingAutoConfiguration

核心代码就是 @ConditionalOnMissingBean(type="okhttp3.OkHttpClient"),表示 Spring BeanFactory 中不包含指定的 bean 时条件匹配,也就是没有启用 okhttp3 时才会进行压缩配置。