在上一篇文章中,简单的介绍了Feign的使用,【Spring Cloud(F版)服务调用Feign】,不是很了解的小伙伴可以前去看一看,Feign在Spring Cloud服务调用非常的方便,所以使用的人也特别多,有必要多开一篇来详细学习一下Feign跟细节的一些功能。
Feign和Ribbon以及Hystrix能很简单的进行整合,这里暂时先不介绍吧,等后面讲到Hystrix的时候再一起说明。
——————————————————————————————————————————————————————
开启GZIP压缩
Spring Cloud Feign支持对请求和响应进行GZIP压缩,以提高通信效率。配置方式如下:
feign:
compression:
request:
# 配置请求GZIP压缩 默认false
enabled: true
# 配置压缩数据大小的下限
min-request-size: 2048
# 配置压缩支持的MIME TYPE
mime-types:
- text/html
- application/xml
- application/json
response:
# 配置响应GZIP压缩 默认false
enabled: true
属性文件配置
配置方式:
feign:
client:
config:
#需要配置的feignName
feignName:
#链接超时时间
connectTimeout: 5000
#读超时时间设置
readTimeout: 5000
#配置Feign日志级别
loggerLevel: FULL
# errorDecoder: #Feign错误解码器
# retryer: #配置重试
#配置拦截器
requestInterceptors:
- com.clarezhou.example.interceptor.MyRequestInterceptor
# encoder: #Feign编码器
# decoder: #Feign解码器
# contract: #Feign Contract配置
Feign请求拦截器:
在进行认证鉴权的时候,不管是jwt,还是security,当使用Feign时就会发现外部请求到服务的时候,Token会丢失,从而认证失败,前一段时间我搭建Spring Cloud + OAuth2 单点登录框架的时候就遇到了这样的问题,解决方法比较简单,就是在拦截器中,向请求的头部中添加Token。
详细的内容我到时候会在另外一个专栏里面介绍。
package com.clarezhou.example.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
/**
* @author clarezhou
* @date 2019/7/30 16:08
**/
@Slf4j
@Configuration
public class MyRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
log.info("请求地址:{}",template.url());
log.info("请求方法:{}",template.method());
log.info("请求参数:{}",template.queryLine());
template.header("Authorization", String.format("%s %s", "Bearer", "123456"));
}
}
开启日志
1、除了上面的配置方式,还是通过以下方式配置开启日志
logging:
level:
com.clarezhou.example.service.HelloService: FULL
2、也可以在主程序入口类中添加@Bean注解
@Bean
Logger.Level feignLogger(){
return Logger.Level.FULL;
}
3、还可以通过@Configuration注解类来开启
package com.clarezhou.example.config;
import feign.Logger;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignServiceConfig {
/**
* Logger.Level
* NONE:不记录任何信息
* BASIC:仅记录请求方法、URL以及响应状态码和执行时间
* HEADERS:除了记录BASIC级别的信息外,还会记录请求和响应的头信息
* FULL:记录所有请求与响应的明细,包括头信息、请求体、元数据
*
* @return
*/
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}