1.简介

OpenFeign基本上就是当前微服务之间调用的事实标准,只需创建一个Rest接口并在该接口上添加注解@FegnCLent即可

2.配置OpenFeign

pom

<!--openfeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

消费端主启动类

@EnableFeignClients//启用feign客户端,定义服务+绑定接口,以声明式的方法优雅而简单的实现服务调用

公共包api interface引入服务

@FeignClient(value = "cloud-payment-service")
{
    @Mapping(***)
    服务内controller一致的路径和函数
}

消费端controller

@Mapping(***)
public ResultData fun(参数){
    return api interface.fun(参数);
}

3.OpenFeign高级特性

3.1 OpenFeign超时控制

OpenFeign默认等待60秒钟,超过后报错

cloud下
    openfeign:
      client:
        config:
          default:
            connectTimeout: 4000 #连接超时时间
            readTimeout: 4000 #读取超时时间
​
          cloud-payment-service:
            connectTimeout: 20000 #连接超时时间
            readTimeout: 20000 #读取超时时间

3.2 OpenFeign重试机制

config下添加

@Configuration
public class FeignConfig
{
    @Bean
    public Retryer myRetryer()
    {
        return Retryer.NEVER_RETRY; //Feign默认配置是不走重试策略的
        //最大请求次数为3(1+2),初始间隔时间为100ms,重试间最大间隔时间为1s
        //return new Retryer.Default(100,1,3);
    }
​
}

3.3 OpenFeign默认HttpClient修改

pom

<!-- httpclient5-->
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version>
</dependency>
<!-- feign-hc5-->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-hc5</artifactId>
    <version>13.1</version>
</dependency>

yml

#  Apache HttpClient5 配置开启
spring:
  cloud:
    openfeign:
      httpclient:
        hc5:
          enabled: true

3.4 OpenFeign请求/响应压缩

对请求和响应进行GZIP压缩

Spring Cloud OpenFeign支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗。

通过下面的两个参数设置,就能开启请求与相应的压缩功能:

spring.cloud.openfeign.compression.request.enabled=true

spring.cloud.openfeign.compression.response.enabled=true

细粒度化设置

对请求压缩做一些更细致的设置,比如下面的配置内容指定压缩的请求数据类型并设置了请求压缩的大小下限,

只有超过这个大小的请求才会进行压缩:

spring.cloud.openfeign.compression.request.enabled=true

spring.cloud.openfeign.compression.request.mime-types=text/xml,application/xml,application/json #触发压缩数据类型

spring.cloud.openfeign.compression.request.min-request-size=2048 #最小触发压缩的大小

yml

openfeign 下
      compression:
        request:
          enabled: true
          min-request-size: 2048 #最小触发压缩的大小
          mime-types: text/xml,application/xml,application/json #触发压缩数据类型
        response:
          enabled: true

3.5 OpenFeign日志打印功能

日志级别

level info
NONE 默认的,不显示任何日志
BASIC 仅记录请求方法、URL、响应状态码及执行时间
HEADERS 除了 BASIC 中定义的信息之外,还有请求和响应的头信息
FULL 除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据

config配置Bean

@Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

yml

# feign日志以什么级别监控哪个接口
logging:
  level:
    com:
      atguigu:
        cloud:
          apis:
            PayFeignApi: debug