spring boot 加入gizp
如果采用jar 的方式不是spring boot 项目:只需在配置文件中开启gzip 压缩就可以了
server.tomcat.remote-ip-header=x-forwarded-for
server.tomcat.protocol-header=x-forwarded-proto
server.tomcat.port-header=X-Forwarded-Port
server.use-forward-headers=true
server.compression.enabled=true
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain
但是如果要部署到tomcat,需要如下对tomcat 安装目录下的conf/server.xml 作如下修改:
<!--
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!--开启gzip-->
<Connector port ="8080" protocol="HTTP/1.1" maxHttpHeaderSize ="8192" maxThreads ="150"
minSpareThreads ="25" maxSpareThreads ="75" enableLookups ="false" redirectPort ="8443" acceptCount ="100"
connectionTimeout ="20000" disableUploadTimeout ="true" URIEncoding ="utf-8"
compression="on" compressionMinSize="2048" noCompressionUserAgents="gozilla, traviata"
compressableMimeType="application/json,application/xml,text/html,text/xml,text/plain"/>
原理:
spring 以jar 的方式发布是采用内置的tomcat运行的, 内部进行一系列的TomcatConnectorCustomizer,EmbededContainerCustomizer 对象的自定义
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer servletContainer) {
((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(256);
String mimeTypes = httpProtocol.getCompressableMimeTypes();
String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
}
}
);
}
};
}
如果采用自己安装的tomcat部署, 就要手动开启这些配置就OK了!!!