openfeign开启gzip压缩需客户端和服务端双向配置,可减少70%以上json/xml响应体积;客户端配feign.compression.request/response,服务端配server.compression,注意mime类型一致和最小压缩阈值。

OpenFeign 开启 GZIP 压缩能显著减少 JSON/XML 等文本类响应体的体积,通常可压缩 70% 以上,特别适合传输大量结构化数据的微服务调用场景。关键在于客户端(Feign)和服务端(Spring Boot)**两端都要配置**,且需注意 MIME 类型匹配和最小压缩阈值。
Feign 客户端侧开启请求/响应压缩
在 consumer 服务的 application.yml 中配置 Feign 的压缩开关和参数:
- 必须显式启用请求和响应压缩:仅开一端无效
-
mime-types 要覆盖实际传输格式,如
application/json、application/xml、text/plain - min-request-size 推荐设为 512 或 1024 字节:避免小数据包因压缩反而变大或增加 CPU 开销
示例配置:
feign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
min-request-size: 512
response:
enabled: true
服务提供方开启 HTTP 响应压缩
Feign 调用的服务端(如 user-service)需在自身 application.yml 中开启 Spring Boot 内置 GZIP 支持:
- compression.enabled 必须为 true
- mime-types 需与 Feign 请求中声明的一致,否则服务端不会压缩
- 建议设置
compression.min-response-size: 1024,防止极小响应被无意义压缩
示例配置:
server:
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,application/xml,application/json
min-response-size: 1024
验证是否生效的关键点
GZIP 是否真正起作用,不能只看配置,要观察真实请求头和响应头:
- Feign 发出的请求必须带
Accept-Encoding: gzip,deflate(Feign 自动添加,无需手动) - 服务端返回响应时,必须含
Content-Encoding: gzip头 - 若没看到该头,检查服务端是否开启了 compression,以及 mime-types 是否匹配
- 若响应体很小(如
进阶:自定义解码器处理压缩响应(可选)
默认情况下,Feign 可自动解压 GZIP 响应,但如果你使用了 ResponseEntity<byte></byte> 或自定义 Decoder,可能需要手动解压:
- 引入
org.springframework.util.CompressionUtils或org.springframework.util.GzipUtils - 在 Decoder 中检测
Content-Encoding: gzip,再调用GzipUtils.decompress(byte[]) - 普通
@GetMapping+String或Object返回类型无需额外处理
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











