目前除了 Spring 4 的 boot 和 Spring 5 里提供了相关应用层面的 Gzip 压缩,其他大部分时候都是通过容器(Tomcat、WAS、Jetty等)来开启 Gzip 压缩,剩下的都是 out of date 的自己写一个 filter 来实现这个功能。这里介绍一个开源的第三方库来实现这个功能。
加入依赖
使用 maven 导入依赖。
com.github.ziplet
ziplet
2.1.2
增加 filter 配置
在 web.xml 中增加配置。
CompressingFilter
com.github.ziplet.filter.compression.CompressingFilter
CompressingFilter
/*
配置项
示例。
CompressingFilter
com.github.ziplet.filter.compression.CompressingFilter
debug
true
debug (optional): 是否输出 debug 信息,默认 false 。
compressionThreshold (optional): 设置开启压缩的最小 response 大小,单位 byte 。设置为 0 时永远开启压缩。默认 1024 。
statsEnabled (optional): 是否统计,详情见 CompressingFilterStats 。
includeContentTypes (optional): 设置针对某种 content type 开启压缩,如 text/html 。在 response 设置了 content type 之后调用。
excludeContentTypes (optional): include 和 exclude 是反义词,所以是设置排除某些 content type 的压缩。
includePathPatterns (optional): 类似 includeContentTypes ,不过是针对的 uri 。支持正则表达式,如 ‘.static.’ 。
excludePathPatterns (optional): 排除特定 uri 的压缩。
includeUserAgentPatterns (optional): 针对特定 UA 的压缩。
excludeUserAgentPatterns (optional): 排除特定 UA 的压缩。
noVaryHeaderPatterns (optional): 类似 includeUserAgentPatterns 。请求中符合配置的 UA 的响应不会包含 vary header 。