Feign支持的配置项以及Feign性能优化

3,478 阅读1分钟

Feign配置

1. Feign配置源码

public static class FeignClientConfiguration {
    private Level loggerLevel;
    private Integer connectTimeout;
    private Integer readTimeout;
    private Class<Retryer> retryer;
    private Class<ErrorDecoder> errorDecoder;
    private List<Class<RequestInterceptor>> requestInterceptors;
    private Map<String, Collection<String>> defaultRequestHeaders;
    private Map<String, Collection<String>> defaultQueryParameters;
    private Boolean decode404;
    private Class<Decoder> decoder;
    private Class<Encoder> encoder;
    private Class<Contract> contract;
    private ExceptionPropagationPolicy exceptionPropagationPolicy;
}   

2. 以上对应的Feign属性配置

feign:
  client:
    config:
      # 想要调用的微服务的名称
      user-center:
        connectTimeout: 5000 # 连接超时时间
        readTimeout: 5000 # 读取超时时间
        loggerLevel: full # 日志级别
        errorDecoder: com.example.SimpleErrorDecoder  # 错误解码器
        retryer: com.example.SimpleRetryer # 重试策略
        requestInterceptors:
          - com.example.FooRequestInterceptor # 拦截器
        defaultQueryParameters: # 指定查询参数
          query: queryValue
        defaultRequestHeaders:  # 指定查询头部
          header: headerValue
        # 是否对404错误码解码
        decode404: false
        encoder: com.example.SimpleEncoder # 编码器
        decoder: com.example.SimpleDecoder # 解码器
        contract: com.example.SimpleContract # 契约

配置全局日志级别

feign:
  client:
    config:
      # 全局配置
      default:
        loggerLevel: full # 日志级别

Feign性能优化

1. 设置连接池

1.1. 搭配httpclient

a. 引入依赖

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>

b. 写配置

feign:
  client:
    config:
      user-center:
        # 日志级别(NONE,BASIC,HEADERS,FULL)
        loggerLevel: full
  httpclient:
    # 让feign使用apache httpclient请求,默认使用的是URLConnection
    enabled: true
    # feign的最大连接数
    max-connections: 200
    # feign单个路径的最大连接数
    max-connections-per-route: 50

1.2. 或者搭配okhttp

a. 引入依赖

<!-- 这里需要手动填写要依赖的版本号 -->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-okhttp</artifactId>
    <version>11.0</version>
</dependency>

b. 写配置

feign:
  client:
    config:
      user-center:
        # 日志级别(NONE,BASIC,HEADERS,FULL)
        loggerLevel: full
  okhttp:
    enabled: true
    # feign的最大连接数
    max-connections: 200
    # feign单个路径的最大连接数
    max-connections-per-route: 50

2. 设置Feign日志级别为NONE或BASIC