设置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,修订节点如下:
- <Connector port="80" protocol="HTTP/1.1"
- connectionTimeout="20000"
- redirectPort="8443" executor="tomcatThreadPool" URIEncoding="utf-8"
- compression="on"
- compressionMinSize="50" noCompressionUserAgents="gozilla, traviata"
- 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写一个简单的测试程序,代码如下:
- @Test
- public void testGzip() {
- HttpClient httpClient = new HttpClient();
- GetMethod getMethod = new GetMethod("http://localhost/admin.jsp");
- try {
- getMethod.addRequestHeader("accept-encoding", "gzip,deflate");
- getMethod.addRequestHeader("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");
- int result = httpClient.executeMethod(getMethod);
- if (result == 200) {
- System.out.println(getMethod.getResponseContentLength());
- String html = getMethod.getResponseBodyAsString();
- System.out.println(html);
- System.out.println(html.getBytes().length);
- }
- } catch (HttpException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- getMethod.releaseConnection();
- }
- }
执行这个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
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- 设置TOMCAT启用GZIP压缩
- tomcat启用gzip压缩
- tomcat启用gzip压缩
- Tomcat启用GZip压缩
- tomcat启用GZIP压缩
- tomcat启用gzip压缩
- Tomcat启用Gzip压缩
- Tomcat启用Gzip压缩功能
- 设计一个4*4魔方程序
- C++对象内存分配问题
- 将PDF转换成为PPT幻灯片怎么转换
- java学习8--DataInputStream,DataOutputStream
- 开源爬虫软件汇总
- 设置TOMCAT启用GZIP压缩
- 分享关于php CI框架使用的一点小总结
- 阿里CDN不支持PUT、DELETE方法的解决方案
- 阿里巴巴 2015 实习笔试题 分布式系统中的RPC请求经常出现乱序的情况 写一个算法来将一个乱序的序列保序输出
- brew install mysql遇到错误
- Android小笔记
- C++反汇编代码分析--函数调用
- 第一行python脚本
- java批量删除,前后台操作