前言:
The next version of the Project will provide support for gzip in order to faster speed of data transmission on the network。
在我们的项目中,添加对gzip的支持,是为了加快数据在网络中的传输速度。
If you need to transfer data using gzip, you must be setting request header "Accept-Encoding"="gzip". Thus, you will get a response, which include the response header name "Content-Encoding" and value "gzip", and need to ungzip the response data. Besides, the response header name "Content-Length" also will be returned.使用gzip,首先要设置请求消息头Accept-Encoding为gzip。
这样,你将会得到一个响应,根据消息头Content-Encoding为gzip你可以知道,传输过来的数据是经过gzip压缩的。另外,消息头Content-Length会告诉你压缩后的数据长度。
正文:
一:仅使用tomcat配置进行相关压缩
(注:仅使用tomcat压缩仅对页面进行压缩,而后端传输数据并没有进行任何压缩)
1.1配置部分
tomcat配置前
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxSwallowSize="-1"/>
tomcat配置后
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/javascript,
application/javascript,text/css,text/plain,text/json"
maxSwallowSize="-1"/>
1.2效果演示部分(看home2数据)
(注:Content-Encoding是gzip的表示是压缩文件)
tomcat压缩前(主要看home2)
tomcat压缩后
第一次刷新-无缓存
第二次刷新-缓存
二:java+tomcat(对传输的数据进行压缩)
2.1:统一定义压缩类
public class GZIPUtils {
public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";
public static byte[] compress(String str, String encoding) {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encoding));
gzip.close();
} catch ( Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}
public static byte[] compress(String str) throws IOException {
return compress(str, GZIP_ENCODE_UTF_8);
}
}
需要压缩部分代码调用压缩类
JsonObject j = new JsonObject();
byte[] output = GZIPUtils.compress(j.toString());
// 设置Content-Encoding,这是关键点!
response.setHeader("Content-Encoding", "gzip");
// 设置字符集
response.setCharacterEncoding("utf-8");
// 设定输出流中内容长度
response.setContentLength(output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
结束语:大家要是没看懂,可以参考以下两篇博客的文章
1:压缩启蒙文章:https://www.cnblogs.com/DDgougou/p/8675504.html?tdsourcetag=s_pctim_aiomsg
2:压缩进阶文章: https://snowolf.iteye.com/blog/643443(推荐)