目前除了 Spring 4 的 boot 和 Spring 5 里提供了相關(guān)應(yīng)用層面的 Gzip 壓縮,其他大部分時候都是通過容器(Tomcat、WAS、Jetty等)來開啟 Gzip 壓縮,剩下的都是 out of date 的自己寫一個 filter 來實現(xiàn)這個功能。這里介紹一個開源的第三方庫來實現(xiàn)這個功能。
加入依賴
使用 maven 導(dǎo)入依賴。
<!-- https://mvnrepository.com/artifact/com.github.ziplet/ziplet -->
<dependency>
<groupId>com.github.ziplet</groupId>
<artifactId>ziplet</artifactId>
<version>2.1.2</version>
</dependency>
其他方式可以在 mvnrepository 找到。
增加 filter 配置
在 web.xml 中增加配置。
<filter>
<filter-name>CompressingFilter</filter-name>
<filter-class>com.github.ziplet.filter.compression.CompressingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CompressingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
配置項
示例。
<filter>
<filter-name>CompressingFilter</filter-name>
<filter-class>com.github.ziplet.filter.compression.CompressingFilter</filter-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</filter>
debug (optional): 是否輸出 debug 信息,默認 false 。
compressionThreshold (optional): 設(shè)置開啟壓縮的最小 response 大小,單位 byte 。設(shè)置為 0 時永遠開啟壓縮。默認 1024 。
statsEnabled (optional): 是否統(tǒng)計,詳情見 CompressingFilterStats 。
includeContentTypes (optional): 設(shè)置針對某種 content type 開啟壓縮,如 text/html 。在 response 設(shè)置了 content type 之后調(diào)用。
excludeContentTypes (optional): include 和 exclude 是反義詞,所以是設(shè)置排除某些 content type 的壓縮。
includePathPatterns (optional): 類似 includeContentTypes ,不過是針對的 uri 。支持正則表達式,如 '.static.' 。
excludePathPatterns (optional): 排除特定 uri 的壓縮。
includeUserAgentPatterns (optional): 針對特定 UA 的壓縮。
excludeUserAgentPatterns (optional): 排除特定 UA 的壓縮。
noVaryHeaderPatterns (optional): 類似 includeUserAgentPatterns 。請求中符合配置的 UA 的響應(yīng)不會包含 vary header 。