posir 发表于 2015-8-8 13:05:36

tomcat下配置gzip

背景:HTTP 压缩可以大大提高浏览网站的速度,它的原理是,在客户端请求网页后,从服务器端将网页文件压缩,再下载到客户端,由客户端的浏览器负责解压缩并浏览。相对于普通的浏览过程HTML ,CSS,Javascript , Text ,它可以节省40%左右的流量。更为重要的是,它可以对动态生成的,包括CGI、PHP , JSP , ASP , Servlet,SHTML等输出的网页也能进行压缩,压缩效率惊人。

  一,对于Tomcat5.0以后的版本是支持对输出内容进行压缩的。使用的是gzip压缩格式

下面是tomcat5.5.20 中的$tomcat_home$/conf/server.xml的原内容

1      < Connectorport =&quot;80&quot;maxHttpHeaderSize =&quot;8192&quot;
2                maxThreads =&quot;150&quot;minSpareThreads =&quot;25&quot;maxSpareThreads =&quot;75&quot;
3                enableLookups =&quot;false&quot;redirectPort =&quot;8443&quot;acceptCount =&quot;100&quot;
4                connectionTimeout =&quot;20000&quot;disableUploadTimeout =&quot;true&quot;URIEncoding =&quot;utf-8&quot;   />
5      
7   
8      

  从上面的第8行内容可以看出,要使用gzip压缩功能,你可以在Connector实例中加上如下属性即可

compression=&quot;on&quot; 打开压缩功能
compressionMinSize=&quot;2048&quot; 启用压缩的输出内容大小,这里面默认为2KB
noCompressionUserAgents=&quot;gozilla, traviata&quot; 对于以下的浏览器,不启用压缩
compressableMimeType=&quot;text/html,text/xml&quot; 压缩类型
我这里的配置内容为:

1   
9      
11   
12      
19

  一旦启用了这个压缩功能后,我们怎么来测试压缩是否有效呢?首先Tomcat是根据浏览器请求头中的accept-encoding来判断浏览器是否支持压缩功能,如果这个值包含有gzip,就表明浏览器支持gzip压缩内容的浏览,所以我们可以用httpclient来写一个这样的简单测试程序

程序代码:

package com.liusoft.dlog4j.test;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

/**
* HTTP客户端测试类
* @author liudong
*/
public class HttpTester {

/**
* @param args
*/
public static void main(String[] args) throws Exception{
HttpClient http = new HttpClient();
GetMethod get = new GetMethod(&quot;http://www.dlog.cn/js/prototype.js&quot;);
try{
get.addRequestHeader(&quot;accept-encoding&quot;, &quot;gzip,deflate&quot;);
get.addRequestHeader(&quot;user-agent&quot;, &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)&quot;);
int er = http.executeMethod(get);
if(er==200){
   System.out.println(get.getResponseContentLength());
   String html = get.getResponseBodyAsString();
   System.out.println(html);
   System.out.println(html.getBytes().length);
}
}finally{
   get.releaseConnection();
}
}

}

  执行这个测试程序,看看它所输出的是什么内容,如果输出的是一些乱码,以及打印内容的长度远小于实际的长度,那么恭喜你,你的配置生效了,你会发现你网站的浏览速度比以前快多了。

  另外你最好对网站所用的javascript和css也进行压缩:)
页: [1]
查看完整版本: tomcat下配置gzip