网站优化——使用gzip压缩文件 有更新!

  |   0 评论   |   394 浏览

简介

    Gzip最早由Jean-loup Gailly和Mark Adler创建,用于UNⅨ系统的文件压缩。我们在Linux中经常会用到后缀为.gz的文件,它们就是GZIP格式的。现今已经成为Internet 上使用非常普遍的一种数据压缩格式,或者说一种文件格式。

编码实现Gzip

压缩

	  public static byte[] gzip(byte[] data) throws Exception {
		byte[] ret = null;
		try ( ByteArrayOutputStream bos = new ByteArrayOutputStream();
				GZIPOutputStream gzip = new GZIPOutputStream(bos);) {
			gzip.write(data);
			gzip.finish();
			gzip.close();
			ret = bos.toByteArray();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

解压

	public static byte[] ungzip(byte[] data) throws Exception {
		byte[] ret = null;
		try ( ByteArrayInputStream bis = new ByteArrayInputStream(data);
				GZIPInputStream gzip = new GZIPInputStream(bis);) {
			
			byte[] buf = new byte[1024];
			int num = -1;
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			while ((num = gzip.read(buf, 0, buf.length)) != -1) {
				bos.write(buf, 0, num);
			}
			gzip.close();
			bis.close();
			ret = bos.toByteArray();
			bos.flush();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

测试

	@Test
	public void test1() throws Exception {
		
		String path = "C:/Users/Admin/Desktop/catalina.out"; //选择任意文件进行压缩
		InputStream in = new FileInputStream(new File(path));
		byte[] bt = new byte[in.available()];
		in.read(bt);
		in.close();
		System.out.println("文件原始大小:\t" + Math.ceil(bt.length / 1024) + "kb");
		
		byte[] ziped = gzip(bt);
		System.out.println("压缩后大小: \t" + Math.ceil(ziped.length / 1024.0) + "kb");
		
		byte[] unziped = ungzip(ziped);
		System.out.println("解压后大小: \t" + Math.ceil(unziped.length / 1024) + "kb");
	}

配置tomcat开启Gzip

修改%TOMCAT_HOME%/conf/server.xml

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

配置Nginx开启Gzip

修改%NGINX_HOME%/conf/nginx.conf

找到如下文本:
 
imagepng
 
 

  • gzip off 开启gzip
     
  • gzip_min_length 1k 启用gzip压缩的最小阀值
     
  • gzip_comp_level 1 gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间
     
  • gzip_types xxx/xxx mime.types 参考W3cSchool—MIME文档
     
  • gzip_vary on 给CDN和代理服务器使用,针对相同url,可以根据头信息返回压缩和非压缩副本
     
  • gzip_disable "MSIE [1-6]\." 禁用IE 6 gzip
     
  • gzip_buffers 32 4k 设置压缩所需要的缓冲区大小
     
  • gzip_http_version 1.1 设置gzip压缩针对的HTTP协议版本




YouY Blog —— 专心做你的烂笔头。访问主页

评论

发表评论

validate