栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > 服务器

如何验证Tomcat Gzip配置是否生效的方法

服务器 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何验证Tomcat Gzip配置是否生效的方法

我们在使用Tomcat优化配置时,都会开始Tomcat的Gzip压缩功能,配置如下:

  

即把以下内容加入到 apache-tomcat-6confserver.xml 中的connector标签中

   

参数说明:

 compression="on" 打开压缩功能
compressionMinSize="2048" 启用压缩的输出内容大小,当被压缩对象的大小>=该值时才会被压缩,这里面默认为2KB
noCompressionUserAgents="gozilla, traviata" 对于以下的浏览器,不启用压缩
compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain,image/gif,image/jpg" 压缩类型

注意:tomcat7以后,js文件的mimetype类型变为了application/Javascript,具体的tomcat7定义的类型可以在:conf/web.xml文件中找到。

我的Tomcat6所以 还是 text/javascript

Tomcat7 js文件的mimetype类型变为了application/javascript
自己注意 配错了起不到压缩的作用哦

那么我们如何测试配置的Gzip压缩功能生效了呢?
答案就是:使用apache HttpClient访问该tomcat加载项目中的一个静态资源(比如一个js文件),然后打印请求的资源内容 或 资源ContentLength,如果打印的资源内容为乱码 或 ContentLength为 -1,则说明gzip生效了。

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

public class GzipTest { 


 
public static void main(String[] args) throws Exception{ 
  HttpClient http = new HttpClient(); 
  GetMethod get = new GetMethod("http://127.0.0.1:9080/membercms/style/shop/js/base.js"); 
  try{ 
  get.addRequestHeader("accept-encoding", "gzip,deflate"); 
  get.addRequestHeader("user-agent", "Mozilla/5.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(); 
   
} 
} 


} 

控制台结果为乱码

说明配置压缩网站的信息成功,此法可能对服务器cpu有些损耗。

Apache 开启Gzip压缩配置:

去掉以下两个 注释#

LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so

在 httpd.conf最后加入

#apache Gzip
 

# Insert filter 

SetOutputFilter DEFLATE 

# Netscape 4.x has some problems... 

BrowserMatch ^Mozilla/4 gzip-only-text/html 

# Netscape 4.06-4.08 have some more problems 

BrowserMatch ^Mozilla/4.0[678] no-gzip 

# MSIE masquerades as Netscape, but it is fine 

BrowserMatch bMSIE !no-gzip !gzip-only-text/html 

# Don't compress images 
SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI .(?:pdf|doc|avi|mov|mp3|rm)$ no-gzip dont-vary

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/js
# Make sure proxies don't deliver the wrong content 

#Header append Vary User-Agent env=!dont-vary 

 

设置完成之后 访问http://tool.chinaz.com/Gzips/ 输入你的网站域名 检测压缩情况。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/181485.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号