Loading

02_Feign使用及其扩展点

Spring Cloud Alibaba快速整合Feign

引入依赖
        <!-- openfeign 远程调用 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
编写调用接口+@FeignClient注解
@FeignClient(value = "mall-order", path = "/order")
public interface OrderFeignService {

    @RequestMapping("/findOrderByUserId/{userId}")
    R findOrderByUserId(@PathVariable("userId") Integer userId);
}
调用端在启动类上添加@EnableFeignClients注解
@SpringBootApplication
@EnableFeignClients //扫描和注册feign客户端bean定义
public class MallUserFeignDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MallUserFeignDemoApplication.class, args);
    }
}
发起调用,像调用本地方式一样调用远程服务
    @Autowired
    OrderFeignService orderFeignService;

    @RequestMapping(value = "/findOrderByUserId/{id}")
    public R findOrderByUserId(@PathVariable("id") Integer id) {
        //feign调用
        return orderFeignService.findOrderByUserId(id);
    }
提示: Feign 的继承特性可以让服务的接口定义单独抽出来,作为公共的依赖,以方便使用。

Spring Cloud Feign扩展

Feign 提供了很多的扩展机制,让用户可以更加灵活的使用。

日志配置

有时候我们遇到 Bug,比如接口调用失败、参数没收到等问题,或者想看看调用性能,就需要配置 Feign 的日志了,以此让 Feign 把请求信息输出来。
定义一个配置类,指定日志级别:
// 注意: 此处配置@Configuration注解就会全局生效,如果想指定对应微服务生效,就不能配置@Configuration
@Configuration
public class FeignConfig {
    /**
     * 日志级别
     * 通过源码可以看到日志等级有 4 种,分别是:
     * NONE:不输出日志。
     * BASIC:只输出请求方法的 URL 和响应的状态码以及接口执行的时间。
     * HEADERS:将 BASIC 信息和请求头信息输出。
     * FULL:输出完整的请求信息。
     *
     * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}
通过源码可以看到日志等级有 4 种,分别是:
NONE【性能最佳,适用于生产】:不记录任何日志(默认值)。
BASIC【适用于生产环境追踪问题】:仅记录请求方法、URL、响应状态代码以及执行时间。
HEADERS:记录BASIC级别的基础上,记录请求和响应的header。
FULL【比较适用于开发及测试环境定位问题】:记录请求和响应的header、body和元数据。

局部配置

让调用的微服务生效,在@FeignClient 注解中指定使用的配置类
//FeignConfig局部配置
@FeignClient(value = "mall-order",path = "/order",configuration = FeignConfig.class)
public interface OrderFeignService {

    @RequestMapping("/findOrderByUserId/{userId}")
    R findOrderByUserId(@PathVariable("userId") Integer userId);
}
在yml配置文件中配置 Client 的日志级别才能正常输出日志,格式是"logging.level.feign接口包路径=debug"
logging:
  level:
    com.yyj.mall.feigndemo.feign: debug
测试:BASIC级别日志

局部配置可以在yml中配置:

对应属性配置类:org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration
feign:
  client:
    config:
      mall-order:  #对应微服务
        loggerLevel: FULL

 契约配置

Spring Cloud 在 Feign 的基础上做了扩展,可以让 Feign 支持 Spring MVC 的注解来调用。原生的 Feign 是不支持 Spring MVC 注解的,如果你想在 Spring Cloud 中使用原生的注解方式来定义客户端也是可以的,通过配置契约来改变这个配置,Spring Cloud 中
默认的是 SpringMvcContract。
修改契约配置,支持Feign原生的注解:
    /**
     * 使用Feign原生的注解配置
     */
    @Bean
    public Contract feignContract() {
        return new Contract.Default();
    }
注意:修改契约配置后,OrderFeignService 不再支持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   #指定Feign原生注解契约配置

通过拦截器实现参数传递(重点)

通常我们调用的接口都是有权限控制的,很多时候可能认证的值是通过参数去传递的,还有就是通过请求头去传递认证信息,比如 Basic 认证方式。
Feign 中我们可以直接配置 Basic 认证:
/**
     * 开启Basic认证
     */
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("yyj","yyj123?");
    }

调用前会配置basic认证:

扩展点:feign.RequestInterceptor

每次 feign 发起http调用之前,会去执行拦截器中的逻辑。 
public interface RequestInterceptor {

/**
* Called for every request. Add data using methods on the supplied {@link
questTemplate}.
*/
void apply(RequestTemplate template);
}
使用场景:
1. 统一添加 header 信息;
2. 对 body 中的信息做修改或替换; 

自定义拦截器实现认证逻辑:

public class FeignAuthRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        // 业务逻辑  模拟认证逻辑
        String access_token = UUID.randomUUID().toString();
        //设置token
        template.header("Authorization", access_token);
    }
}

全局配置:

    /**
     * 自定义拦截器
     */
    @Bean
    public FeignAuthRequestInterceptor feignAuthRequestInterceptor() {
        return new FeignAuthRequestInterceptor();
    }

测试:

可以在yml中局部配置:

feign:
  client:
    config:
      mall-order:  #对应微服务
        loggerLevel: FULL
        requestInterceptors[0]:  #配置拦截器
          FeignAuthRequestInterceptor
mall-order端可以通过 @RequestHeader获取请求参数,建议在filter,interceptor中处理 

超时时间配置

通过 Options 可以配置连接超时时间和读取超时时间,Options 的第一个参数是连接的超时时间(ms),默认值是 2s;第二个是请求处理的超时时间(ms),默认值是 5s。 

全局配置:

    /**
     * 连接超时时间和请求超时时间配置
     */
    @Bean
    public Request.Options options() {
        return new Request.Options(3000, 4000);
    }

yml中配置:

feign:
  client:
    config:
      mall-order:  #对应微服务
        loggerLevel: FULL
        # 连接超时时间,默认2s
        connectTimeout: 3000
        # 请求处理超时时间,默认5s
        readTimeout: 10000
补充说明: Feign的底层用的是Ribbon,但超时时间以Feign配置为准。

客户端组件配置 

Feign 中默认使用 JDK 原生的 URLConnection 发送 HTTP 请求,使用的是jdk1.1的包,比较古老性能较差,我们可以集成别的组件来替换掉 URLConnection,比如 Apache HttpClient,OkHttp。 

Feign发起调用真正执行逻辑:feign.Client#execute (扩展点) 

默认实现:

配置Apache HttpClient:

引入依赖
        <!-- Apache HttpClient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.7</version>
        </dependency>
        <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:

配置 OkHttp

引入依赖 
        <!-- feign-okhttp -->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-okhttp</artifactId>
        </dependency>
然后修改yml配置,将 Feign 的 HttpClient 禁用,启用 OkHttp,配置如下:
  #feign 使用 okhttp
  httpclient:
    enabled: false
  okhttp:
    enabled: true
关于配置可参考源码: org.springframework.cloud.openfeign.FeignAutoConfiguration :

测试:调用会进入feign.okhttp.OkHttpClient#execute

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 时才会进行压缩配置。 

编码器解码器配置

Feign 中提供了自定义的编码解码器设置,同时也提供了多种编码器的实现,比如 Gson、Jaxb、Jackson。我们可以用不同的编码解码器来处理数据的传输。如果你想传输 XML 格式的数据,可以自定义 XML 编码解码器来实现获取使用官方提供的 Jaxb。
扩展点:Encoder & Decoder

Java配置方式

配置编码解码器只需要在 Feign 的配置类中注册 Decoder 和 Encoder 这两个类即可:
    @Bean
    public Decoder decoder() {
        return new JacksonDecoder();
    }

    @Bean
    public Encoder encoder() {
        return new JacksonEncoder();
    }

yml配置方式 

feign:
  client:
    config:
      mall-order:  #对应微服务
        loggerLevel: FULL
        # 配置编解码器
        encoder: feign.jackson.JacksonEncoder
        decoder: feign.jackson.JacksonDecoder

 

posted @ 2023-04-24 00:11  1640808365  阅读(75)  评论(0编辑  收藏  举报