在Tomcat上直接配置GZIP压缩

tomcat本身在5.0版本以后是支持内容压缩的,它使用的是gzip的压缩格式,我们先来看Tomcat文档中对下面两个配置的注解(红色粗体字部分)

compressableMimeType

The value is a comma separated list of MIME types for which HTTP compression may be used. The default value istext/html,text/xml,text/plain.

compression

The Connector may use HTTP/1.1 GZIP compression in an attempt to save server bandwidth. The acceptable values for the parameter is "off" (disable compression), "on" (allow compression, which causes text data to be compressed), "force" (forces compression in all cases), or a numerical integer value (which is equivalent to "on", but specifies the minimum amount of data before the output is compressed). If the content-length is not known and compression is set to "on" or more aggressive, the output will also be compressed. If not specified, this attribute is set to "off".

这两个配置是在servere.xml中的Connector部分,第一个配置是指定Tomcat压缩哪些内容,第二个配置是指示Tomcat是否启用压缩,默认是关闭的。所以假设我们要让Tomcat在默认的8080端口上的输出内容进行压缩,我们的配置应该是:

    <Connector port="8080" protocol="HTTP/1.1" 
               maxThreads="150" connectionTimeout="20000" 
               redirectPort="8443" compression="on"/>

一旦启用了这个压缩功能后,我们怎么来测试压缩是否有效呢?首先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("http://www.dlog.cn/js/prototype.js");
  try{
   get.addRequestHeader("accept-encoding", "gzip,deflate");
   get.addRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");
   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也进行压缩:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值