设置TOMCAT启用GZIP压缩

来源:互联网 发布:林冉网络班教程 编辑:程序博客网 时间:2024/05/14 08:24

原文:http://blog.csdn.net/hbcui1984/article/details/5666327


原理简介

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

配置方法

Tomcat5.0以后的版本是支持对输出内容进行压缩的,使用的是gzip压缩格式 。
 
修改%TOMCAT_HOME%/conf/server.xml,修订节点如下:
[xhtml] view plaincopy
  1. <Connector port="80" protocol="HTTP/1.1"   
  2.            connectionTimeout="20000"   
  3.            redirectPort="8443" executor="tomcatThreadPool" URIEncoding="utf-8"   
  4.                        compression="on"   
  5.                        compressionMinSize="50" noCompressionUserAgents="gozilla, traviata"   
  6.                        compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain" />  
 

  从上面节点的属性可以看出,要使用gzip压缩功能,你需要在Connector节点中加上如下属性

  • compression="on" 打开压缩功能 
  • compressionMinSize="50" 启用压缩的输出内容大小,默认为2KB 
  • noCompressionUserAgents="gozilla, traviata" 对于以下的浏览器,不启用压缩 
  • compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain" 哪些资源类型需要压缩

测试方法

启用了TOMCAT这个压缩功能后,我们如何来测试压缩是否有效呢?
首先Tomcat是根据浏览器请求头中的accept-encoding来判断浏览器是否支持压缩功能,如果这个值包含有gzip,就表明浏览器支持gzip压缩内容的浏览,我们可以用两种方法来验证压缩是否生效。

通过浏览器直接请求

       大家直接通过浏览器访问启用了压缩配置的服务器,然后通过抓包工具查看抓到的数据包,如果内容有很多你看不懂,就说明已经启用压缩功能了。

通过程序模拟请求

我们用httpclient写一个简单的测试程序,代码如下:
[java] view plaincopy
  1. @Test  
  2. public void testGzip() {  
  3.         HttpClient httpClient = new HttpClient();  
  4.         GetMethod getMethod = new GetMethod("http://localhost/admin.jsp");  
  5.         try {  
  6.                 getMethod.addRequestHeader("accept-encoding""gzip,deflate");  
  7.                 getMethod.addRequestHeader("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");  
  8.                 int result = httpClient.executeMethod(getMethod);  
  9.                 if (result == 200) {  
  10.                         System.out.println(getMethod.getResponseContentLength());  
  11.                         String html = getMethod.getResponseBodyAsString();  
  12.                         System.out.println(html);  
  13.                         System.out.println(html.getBytes().length);  
  14.                 }  
  15.         } catch (HttpException e) {  
  16.                 e.printStackTrace();  
  17.         } catch (IOException e) {  
  18.                 e.printStackTrace();  
  19.         } finally {  
  20.                 getMethod.releaseConnection();  
  21.         }  
  22. }  

  执行这个junit程序,看看它所输出的是什么内容,如果输出的是一些乱码,并且打印内容的长度远小于实际的长度,就说明我们的配置生效了,通过一些其它验证工具,会发现网站浏览速度会明显提升。

备注:如果发现内容没有被压缩,可以考虑调整compressionMinSize大小,如果请求资源小于这个数值,则不会启用压缩。


http请求例子:

public static String doGet(String url, String charset, int timeout)throws Exception {// 记录所有的请求到其他系统的url// if (logger.isInfoEnabled())// logger.info("url to b2c api: " + url);/* 建立HTTPGet对象 */String strResult = "";HttpResponse httpResponse = null;HttpClient httpClient = null;HttpGet httpRequest = null;/* 发送请求并等待响应 */try {long start = System.currentTimeMillis();httpClient = getHttpClient(timeout);httpRequest = new HttpGet(url);// specify some common header, like IP, reference, accepthttpRequest.addHeader("Referer", "http://apps-show.api.vip.com/");        httpRequest.addHeader("Accept-Encoding", "gzip, deflate");                // 增加IP转发功能        String client_id = ip_session.get();        if (StringUtils.isEmpty(client_id)) {            client_id = _127_0_0_1;        }        httpRequest.setHeader("X-Forwarded-For", client_id);        if (logger.isDebugEnabled()) {            logger.debug(">>>> request ip: " + client_id);        }httpResponse = httpClient.execute(httpRequest);// 查看响应状态 如果不是正常状态 则主动abort请求并返回if (isSuccess(httpResponse.getStatusLine().getStatusCode()) == false) {httpRequest.abort();logger.warn("target return error status, the url is :" + url);return null;}if (httpResponse.getEntity() != null) {byte[] bytes = getResponseEntityAsByteArray(httpResponse);Header contentEncodingHeader = httpResponse                .getFirstHeader("Content-Encoding");        if (contentEncodingHeader != null                && contentEncodingHeader.getValue().toLowerCase()                        .indexOf("gzip") > -1) {            bytes = EntityUtils.toByteArray(new GzipDecompressingEntity(                    httpResponse.getEntity()));        } else {            bytes = EntityUtils.toByteArray(httpResponse.getEntity());        }/*if (logger.isInfoEnabled()) {String responseMinStr = logHttpRespone(bytes, charset);logger.info("HTTP GET : " + url + ",response is ["+ responseMinStr + "],length is ["+ (bytes != null ? bytes.length : 0) + "]");}*/strResult = new String(bytes, charset);//使用的是一个String对象,如果使用 Sting str = "aaaa";的形式定义一个字符串,那么双引号里面的ASCII字符最多只能有 65534 个// strResult = EntityUtils.toString(httpResponse.getEntity(),// charset);//过滤特殊字符if (null != strResult) {    strResult = strResult.replace("'", "'");    strResult = strResult.replace("&", "&");    strResult = strResult.replace(" ", " ");        }}long offset = System.currentTimeMillis() - start;if (offset > warnTime)logConnectionStats(offset, url);} catch (Exception e) {logger.error("http get error with url " + url, e);if (httpRequest != null) {httpRequest.abort();}throw e;}return strResult;}

 gzip 请求例子:

  public static void main(String[] args) {        try {            HttpClient httpClient = new DefaultHttpClient();            try {                HttpGet httpRequest = new HttpGet(                        "http://192.168.32.38:8080/apps-api/brands?warehouse=VIP_SH&app_version=&app_id=8&sort_type=rs&rs_channel_id=0&rs_user_group=0&app_name=shop_ios&sell_type=1&t=12");                httpRequest.addHeader("accept-encoding", "gzip,deflate");                httpRequest                        .addHeader(                                "user-agent",                                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");                HttpResponse result = httpClient.execute(httpRequest);                                byte[] b=EntityUtils.toByteArray(new GzipDecompressingEntity(                        result.getEntity()));                String str=new String(b, "utf-8");                System.out.println(b.length);                                HttpResponse result2 = httpClient.execute(httpRequest);                byte[] b2=EntityUtils.toByteArray(result2.getEntity());                System.out.println(b2.length);                                System.out.println(result.getEntity().getContentLength());                System.out.println(str);                                /*int a=0;                if(a=1);*/                                Header contentEncodingHeader = result.getFirstHeader("Content-Encoding");               // byte[] bytes = null;                System.out.println(contentEncodingHeader.getValue());                            } catch (Exception e) {                e.printStackTrace();            } finally {            }        } catch (Exception e) {            e.printStackTrace();        }    }


0 0
原创粉丝点击