服务器使用Gzip压缩数据,加快网络传输 博客分类: java web开发 javaGzip压缩数据
程序员文章站
2024-03-24 15:13:28
...
服务器使用Gzip压缩数据,加快网络传输,提高页面性能。使用方法也很简单,在web.xml进行过滤器的配置即可,如下所示。
<filter> <filter-name>gzipFilter</filter-name> <filter-class> net.sf.ehcache.constructs.web.filter.GzipFilter </filter-class> </filter> <filter-mapping> <filter-name>gzipFilter</filter-name> <url-pattern>*.js</url-pattern> </filter-mapping> <filter-mapping> <filter-name>gzipFilter</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping> <filter-mapping> <filter-name>gzipFilter</filter-name> <url-pattern>*.gif</url-pattern> </filter-mapping> <filter-mapping> <filter-name>gzipFilter</filter-name> <url-pattern>*.css</url-pattern> </filter-mapping>
当然,还要引入相关的两个jar包,ehcache-web-2.0.4.jar和ehcache.jar。
使用gzip,首先要设置请求消息头Accept-Encoding为gzip。这样,你将会得到一个响应,根据消息头Content-Encoding为gzip你可以知道,传输过来的数据是经过gzip压缩的。另外,消息头Content-Length会告诉你压缩后的数据长度。
反编译看到GzipFilter.java的doFilter方法如下,有设置Content-Length。
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws Exception { if ((!(isIncluded(request))) && (acceptsEncoding(request, "gzip")) && (!(response.isCommitted()))) { if (LOG.isDebugEnabled()) { LOG.debug(request.getRequestURL() + ". Writing with gzip compression"); } ByteArrayOutputStream compressed = new ByteArrayOutputStream(); GZIPOutputStream gzout = new GZIPOutputStream(compressed); GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout); wrapper.setDisableFlushBuffer(true); chain.doFilter(request, wrapper); wrapper.flush(); gzout.close(); if (response.isCommitted()) { return; } switch (wrapper.getStatus()) { case 204: case 205: case 304: return; } byte[] compressedBytes = compressed.toByteArray(); boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request); boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus()); if ((shouldGzippedBodyBeZero) || (shouldBodyBeZero)) { response.setContentLength(0); return; } ResponseUtil.addGzipHeader(response); if (this.setVaryHeader) { ResponseUtil.addVaryAcceptEncoding(wrapper); } response.setContentLength(compressedBytes.length); response.getOutputStream().write(compressedBytes); } else { if (LOG.isDebugEnabled()) { LOG.debug(request.getRequestURL() + ". Writing without gzip compression because the request does not accept gzip."); } chain.doFilter(request, response); } }
进一步看ResponseUtil.addGzipHeader方法,有设置消息头Content-Encoding为gzip。
public static void addGzipHeader(HttpServletResponse response) throws ResponseHeadersNotModifiableException { response.setHeader("Content-Encoding", "gzip"); boolean containsEncoding = response.containsHeader("Content-Encoding"); if (!(containsEncoding)) throw new ResponseHeadersNotModifiableException("Failure when attempting to set Content-Encoding: gzip"); }
配置好后,要在浏览器端验证是否做了压缩,可以安装http Watch工具,在IE浏览器中查看,如下所示。
未配置gzip压缩前:
配置gzip压缩后:可以看到压缩比例
PS:网上看到用Java实现的gzip
GetMethod method = new GetMethod(url);//生成一个get方法实例 method.setQueryString(queryString);//设置查询字符串 method.addRequestHeader("Accept-Encoding", "gzip");//设置接受响应消息为gzip HttpClient client = new HttpClient();//生成执行get方法的客户端实例 client.executeMethod(method);//执行get方法 InputStream in = method.getResponseBodyAsStream();//获取响应消息体 Header contentEncoding = method.getResponseHeader("Content-Encoding");//获取消息头Content-Encoding判断数据流是否gzip压缩过 if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { GZIPInputStream gzipIn = new GZIPInputStream(in); int len = Integer.parseInt(method.getResponseHeader("Content-Length").getValue()); byte[] b = new byte[len]; gzipIn.read(b); String json = new String(b); System.out.println(json); }
使用gzip在服务器端压缩数据的例子
byte[] result = data.getBytes("UTF-8"); if(response.getHeader("Accept-Encoding").equalsIgnoreCase("gzip")) { // System.out.println("Before compression, the data size is :"+ result.length); // Using gzip compress the data ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gout = new GZIPOutputStream(out); gout.write(json.getBytes("UTF-8")); gout.close(); result = out.toByteArray(); // System.out.println("After compression, the data size is "+gzipResult.length); this.getResp().setHeader("Content-Encoding","gzip"); this.getResp().setHeader("Content-Length", result.length+""); } response.getOutputStream().write(result);