Spring Boot 默认使用嵌入式 Tomcat 服务器,可通过配置文件对其进行 Gzip 压缩的设置。
配置文件:
server.compression.enabled=true
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
server.compression.min-response-size=1024
其中:
server.compression.enabled=true
:启用压缩功能。server.compression.mime-types
:指定需要进行压缩的 MIME 类型,这里列出了常见的文本和脚本类型。server.compression.min-response-size
:设置触发压缩的最小响应大小,单位为字节,这里设置为 1024 字节,即只有响应大小超过 1KB 才会进行压缩。
验证配置:
启动 Spring Boot 应用程序后,当客户端发起请求时,如果响应满足配置的条件,服务器会自动对响应进行 Gzip 压缩。可以使用浏览器开发者工具(如 Chrome 的开发者工具)查看响应头中是否包含 Content-Encoding: gzip
字段来验证压缩是否生效。