|
# 這兩篇文章主要介紹在apache http server下如何使用mod_deflate模塊來壓縮http響應(yīng)內(nèi)容,最大限度的減小網(wǎng)絡(luò)流量,然而當(dāng)我們僅僅是使用tomcat服務(wù)器時候,更多的文章是通過自行編寫一些代碼來實現(xiàn)輸出內(nèi)容的壓縮,其實tomcat本身在5.0版本以后是支持內(nèi)容壓縮的,它使用的是gzip的壓縮格式,我們先來看 Tomcat文檔中對下面兩個配置的注解(紅色粗體字部分) compressableMimeType The value is a comma separated list of MIME types for which HTTP compression may be used. The default value is text/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壓縮哪些內(nèi)容,第二個配置是指示Tomcat是否啟用壓縮,默認(rèn)是關(guān)閉的。所以假設(shè)我們要讓Tomcat在默認(rèn)的8080端口上的輸出內(nèi)容進(jìn)行壓縮,我們的配置應(yīng)該是: <Connector port="8080" protocol="HTTP/1.1" maxThreads="150" connectionTimeout="20000" redirectPort="8443" compression="on"/> 一旦啟用了這個壓縮功能后,我們怎么來測試壓縮是否有效呢?首先Tomcat是根據(jù)瀏覽器請求頭中的accept-encoding來判斷瀏覽器是否支持壓縮功能,如果這個值包含有g(shù)zip,就表明瀏覽器支持gzip壓縮內(nèi)容的瀏覽,所以我們可以用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./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(); } } } 執(zhí)行這個測試程序,看看它所輸出的是什么內(nèi)容,如果輸出的是一些亂碼,以及打印內(nèi)容的長度遠(yuǎn)小于實際的長度,那么恭喜你,你的配置生效了,你會發(fā)現(xiàn)你網(wǎng)站的瀏覽速度比以前快多了。 另外你最好對網(wǎng)站所用的javascript和css也進(jìn)行壓縮:) |
|
|