1 设置超时时间
OpenFeign 底层内置了 Ribbon 框架,并且使用了 Ribbon 的请求连接超时时间和请求处理超时时间作为其超时时间,而 Ribbon 默认的请求连接超时时间和请求处理超时时间都是 1s 。
通过以下任意两种方式配置 OpenFeign 的超时时间 :
1.1 设置Ribbon超时时间
在项目配置文件 application.yml 中添加以下配置:
ribbon:
ReadTimeout: 5000 # 请求连接的超时时间
ConnectionTimeout: 10000 # 请求处理的超时时间
1.2 设置OpenFeign超时时间
在项目配置文件 application.yml 中添加以下配置:
feign:
client:
config:
default: # 设置的全局超时时间
connectTimeout: 2000 # 请求连接的超时时间
readTimeout: 5000 # 请求处理的超时时间
2 请求连接优化
OpenFeign 底层通信组件默认使用 JDK 自带的 URLConnection 对象进行 HTTP 请求的,没有使用连接池,性能较差。可以将 OpenFeign 的通讯组件,手动替换成像 Apache HttpClient 或 OKHttp 这样的专用通信组件,这些的专用通信组件自带连接池可以更好地对 HTTP 连接对象进行重用与管理,同时也能大大的提升 HTTP 请求的效率。
2.1 引入Apache HttpClient依赖
<!-- 添加 openfeign 框架依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 添加 httpclient 框架依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2.2 开启Apache HttpClient使用
feign:
httpclient:
enabled: true # 开启HttpClient(默认开启)
验证是否生效:SynchronousMethodHandler.invoke() 中打断点
3 数据压缩
3.1 consumer-------provider 的gzip压缩
feign:
compression:
request:
enabled: true # 开启请求数据的压缩功能
mime-types: text/xml,application/xml, application/json # 压缩类型(拥有默认值 {"text/html", "text/xml", "text/plain", "text/css", "text/javascript", "application/javascript", "application/json", "application/xml"})
min-request-size: 1024 # 最小压缩值标准,当数据大于 1024 才会进行压缩(拥有默认值)
response:
enabled: true # 开启响应数据压缩功能
3.2 浏览器-------consumer的gzip压缩
server:
compression:
enabled: true
mime-types: text/xml,application/xml, application/json # 压缩类型(拥有默认值 {"text/html", "text/xml", "text/plain", "text/css", "text/javascript", "application/javascript", "application/json", "application/xml"})
4 日志优化
OpenFeign 提供了日志增强功能,它的日志级别有以下几个:
NONE:默认的,不显示任何日志。
BASIC:仅记录请求方法、URL、响应状态码及执行时间。
HEADERS:除了 BASIC 中定义的信息之外,还有请求和响应的头信息。
FULL:除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据。
logging:
level:
com.powernode.feign: debug #com.powernode.feign为OpenFeign接口所在的包名
feign:
client:
config:
default:
loggerLevel: full #开启feign的日志
注意!!! 开启日志后使用 1.2 设置OpenFeign超时时间中的方式重置超时时间