一、gzip简介
Gzip是若干种文件压缩程序的简称,通常指GNU计划的实现,此处的gzip代表GNU zip。也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。在1992年10月31日第一次公开发布,版本号0.1,1993年2月,发布了1.0版本。OpenBSD中所包含的gzip版本实际上是compress程序,其对gzip文件的支持在OpenBSD 3.4中被添加,此处的g代表免费(gratis)
GZIP最早由Jean-loup Gailly和Mark Adler创建,用于UNⅨ系统的文件压缩。我们在Linux中经常会用到后缀为.gz的文件,它们就是GZIP格式的。现今已经成为Internet 上使用非常普遍的一种数据压缩格式,或者说一种文件格式。HTTP协议上的GZIP编码是一种用来改进WEB应用程序性能的技术。大流量的WEB站点常常使用GZIP压缩技术来让用户感受更快的速度。这一般是指WWW服务器中安装的一个功能,当有人来访问这个服务器中的网站时,服务器中的这个功能就将网页内容压缩后传输到来访的电脑浏览器中显示出来.一般对纯文本内容可压缩到原大小的40%.这样传输就快了,效果就是你点击网址后会很快的显示出来.当然这也会增加服务器的负载. 一般服务器中都安装有这个功能模块的。
二、网站使用,我用的是过滤器,对于使用springmvc、springboot框架同样适用
1、web.xml配置
GZipFilter
GZipFilter
com.jya.filter.GZipFilter
GZipFilter
*.js
GZipFilter
*.css
GZipFilter
*.jpg
GZipFilter
*.png
GZipFilter
*.gif
GZipFilter
*.jpeg
2、java代码public class GZipFilter implements Filter{
private ServletContext ctx;
private Logger logger = Logger.getLogger(GZipFilter.class.getName());
private String contextPath;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
String accept = req.getHeader("Accept-Encoding");
InputStream in = null;
contextPath = ctx.getContextPath();
uri = uri.substring(contextPath.length());
if (accept != null && accept.contains("gzip") && (in = ctx.getResourceAsStream(uri + ".gz")) != null) {
logger.info("start getting gzip file "+uri);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int read = 0;
while ((read = in.read(b)) >= 0) {
bout.write(b, 0, read);
}
in.close();
res.setHeader("Content-Encoding", "gzip");
res.setContentType("application/java;charset=UTF-8");
res.setContentLength(bout.size());
ServletOutputStream out = res.getOutputStream();
out.write(bout.toByteArray());
out.flush();
logger.info("finish getting gzip file "+uri);
return;
} else {
chain.doFilter(request, response);
}
}
public void init(FilterConfig config) throws ServletException {
ctx = config.getServletContext();
}
}
3、tomcat也同样支持gzip压缩,需要修改server.xml配置
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/java,
application/java,text/css,text/plain,text/json"/>
4、如何判断gzip是否生效
打开网页,按12,随便找个静态文件请求,看到下面红框即表示gzip已经生效