gzip壓縮

有端和服務器的數據傳輸量太大,導致網絡傳輸慢問題,有以下方案,一個是讓tomcat去做數據的壓縮,另外一個是使用gzip對參數壓縮。


一,tomcat加上gzip壓縮配置

    配置:在tomcat的server.xml中配置以下信息

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"  

                 compression="on"   //是否啓動壓縮

               compressionMinSize1="2048"  //最小開始壓縮的大小
               noCompressionUserAgents="gozilla, traviata"  //不壓縮的瀏覽器
               compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain,application/json,text/json" //content-type類型設定

       />

    性能:沒有加此配置項119M的json數據,print到瀏覽器上耗時1.4min左右,加上配置項之後50s左右,減小40%左右。


二,數據傳輸參數壓縮


    源字符串:892MB

    壓縮後字符串:3MB
    解壓前字符串:3MB
    解壓後字符串:892MB
    壓縮耗時:8631ms,解壓耗時:4354ms

    

package com.try2better.daily.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.try2better.daily.util.gzip.GzipUtils;


@Controller
@RequestMapping("/gzip")
public class GZipController {
	
    @ResponseBody
    @RequestMapping(value = "/get")
    public JSONArray get() throws Exception {
        return GzipUtils.getTestData();
    }
    
    @ResponseBody
    @RequestMapping(value = "/fetch",method = RequestMethod.POST)
    public byte[] fetch(){
        return GzipUtils.gzip(GzipUtils.getTestData().toJSONString());
    }
    
    @ResponseBody
    @RequestMapping(value = "/receive",method = RequestMethod.POST)
    public String receive(@RequestBody byte[] byt){
    	String sss =  GzipUtils.ungzip(byt);
    	System.out.println(sss);
    	return sss;
    }

    @ResponseBody
    @RequestMapping(value = "/set1")
    public int set1(@RequestBody String jsonString){
        JSONArray jsonArray = JSONArray.parseArray(jsonString);
        System.out.println(jsonArray.size());
        return jsonArray.size();
    }

    @ResponseBody
    @RequestMapping(value = "/set2")
    public int set2(@RequestBody JSONArray jsonArray){
    	System.out.println(jsonArray.size());
       return jsonArray.size();
    }



}


    

package com.try2better.daily.util.gzip;


public class Main {
	
	public static void main(String[] args) throws Exception {
		//get
		byte[] dd = GzipHttpUtil.getInstance().sendHttpPost("http://127.0.0.1:8888/gzip/fetch");
		String dddd = GzipUtils.ungzip(dd);
		System.out.println(dddd);
		
		//set
		byte[] sss = GzipUtils.gzip(dddd);
		GzipHttpUtil.getInstance().sendHttpPostByteArrayResult("http://127.0.0.1:8888/gzip/receive", sss);
	}
}



    

package com.try2better.daily.util.gzip;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class GzipHttpUtil {  
	
	private static final Integer TIMEOUT = 15000;
	private static final String ENCODE = "UTF-8";
       
    private static GzipHttpUtil instance = null; 
    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).build();
    
    private GzipHttpUtil(){
    	
    }   
    
    public static GzipHttpUtil getInstance(){    
    	if (instance == null) {    
    		instance = new GzipHttpUtil();    
        }    
        return instance;    
    }    
    
	/**  
	 * 發送 post請求  
	 * @param httpUrl 地址  
	 */    
	public byte[] sendHttpPost(String httpUrl) {    
	    HttpPost httpPost = new HttpPost(httpUrl);// 創建httpPost   
	    return sendHttpPostByteArrayResult(httpPost);    
	}    
            
	/**  
	 * 發送 post請求  
	 * @param httpUrl 地址  
	 * @param params 
	 */    
	public byte[] sendHttpPostByteArrayResult(String httpUrl, byte[] params) {    
	    HttpPost httpPost = new HttpPost(httpUrl);// 創建httpPost      
	    try {    
	    	//設置參數    
	        ByteArrayEntity arrayEntity = new ByteArrayEntity(params);  
	        httpPost.setEntity(arrayEntity);  
	    } catch (Exception e) {    
	        e.printStackTrace();    
	    }    
	    return sendHttpPostByteArrayResult(httpPost);    
	}        
	
	public String sendHttpPostStringResult(String httpUrl, byte[] params) {  
		byte[] bytes = sendHttpPostByteArrayResult(httpUrl,params);
		if(bytes != null){
			try {
				return new String(bytes,ENCODE);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
	    return null;        
	}  
	
	/**  
	 * 發送 post請求  
	 * @param httpUrl 地址  
	 * @param maps 參數  
	 */    
	public byte[] sendHttpPost(String httpUrl, Map<String,String> maps) {    
	    HttpPost httpPost = new HttpPost(httpUrl);// 創建httpPost     
		// 創建參數隊列      
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();    
		for (String key : maps.keySet()) {    
		    nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));    
		}    
		try {    
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, ENCODE));    
	    } catch (Exception e) {    
	        e.printStackTrace();    
	    }    
	    return sendHttpPostByteArrayResult(httpPost);    
	}          
	/**  
	 * 發送Post請求  
	 * @param httpPost  
	 * @return  
	 */    
	private byte[] sendHttpPostByteArrayResult(HttpPost httpPost) {    
		CloseableHttpClient httpClient = null;    
	    CloseableHttpResponse response = null;    
	    HttpEntity entity = null;    
	    byte[] responseContent = null;    
	    try {    
	        // 創建默認的httpClient實例.    
			httpClient = HttpClients.createDefault();    
			httpPost.setConfig(requestConfig);   
			// 執行請求    
			response = httpClient.execute(httpPost);    
			entity = response.getEntity();   
			responseContent = EntityUtils.toByteArray(entity);  
	    } catch (Exception e) {    
	    	e.printStackTrace();    
	    } finally {    
	    	try {    
	    		// 關閉連接,釋放資源    
	            if (response != null) {    
	                response.close();    
	            }    
	            if (httpClient != null) {    
	                httpClient.close();    
	            }    
	        } catch (IOException e) {    
	            e.printStackTrace();    
	        }    
	    }    
	    return responseContent;    
	}    
}


    

package com.try2better.daily.util.gzip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class GzipUtils {
	
	private static final String ENCODE = "UTF-8";
	
	public static byte[] gzip(String str) {  
		if(str == null){
			return null;
		}
		GZIPOutputStream gzip = null;
		ByteArrayOutputStream bos = null;
		try {
			byte[] data = str.getBytes(ENCODE);
			System.out.println("源字符串:" + data.length / 1024 /1024 + "MB");
		    bos = new ByteArrayOutputStream();  
	        gzip = new GZIPOutputStream(bos);  
	        gzip.write(data);  
	        gzip.finish();  
	        byte[] ret = bos.toByteArray(); 
	        System.out.println("壓縮後字符串:" + ret.length / 1024 /1024 + "MB");
	        return ret;  
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(gzip != null){
					gzip.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}  
			try {
				if(bos != null){
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}  
		}
		return null;
    }  
	  
    public static String ungzip(byte[] data) { 
    	if(data == null || data.length == 0){
    		return null;
    	}
    	GZIPInputStream gzip = null;
    	ByteArrayOutputStream bos = null;
    	ByteArrayInputStream bis = null;
    	try {
    		System.out.println("解壓前字符串:" + data.length / 1024 /1024 + "MB");
            bis = new ByteArrayInputStream(data);  
            gzip = new GZIPInputStream(bis);  
            byte[] buf = new byte[1024];  
            int num = -1;  
            bos = new ByteArrayOutputStream();  
            while ((num = gzip.read(buf, 0, buf.length)) != -1) {  
                bos.write(buf, 0, num);  
            }  
            
            byte[] ret = bos.toByteArray(); 
            System.out.println("解壓後字符串:" + ret.length / 1024 /1024 + "MB");
            bos.flush();  
            
            return new String(ret,ENCODE);  
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(gzip != null){
					gzip.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}  
            try {
            	if(bis != null){
            		bis.close();
            	}
			} catch (IOException e) {
				e.printStackTrace();
			}  
            try {
            	if(bos != null){
            		bos.close();
            	}
			} catch (IOException e) {
				e.printStackTrace();
			}  
		}
    	return null;
    }  
	    
    public static JSONArray getTestData(){
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < 3; i++) {
            JSONObject json = new JSONObject();
            json.put("id",i);
            json.put("username","周暉" + i);
            json.put("sex","m");
            json.put("content","這曾是他最熟悉的,而今,已是他最陌生的。32歲的亨利就坐在那裏,深情的目光望過去,都是自己22歲的影子。380場比賽,226個進球,4座英超金靴,2座英超獎盃,49場不敗。"
            		+ "歷史最佳射手,海布里的最後一戰,海布里的最後一吻。當煙花升起的時刻,那個曾屬於亨利的海布里國王時代不會隨年華逝去,而只會在年華的飄零中常常記起。");
            jsonArray.add(json);
        }
        return jsonArray;
    }
	    
    public static void main(String[] args) throws Exception {  
    	String sss = getTestData().toJSONString();
    	byte[] b = gzip(sss);
    	System.out.println(ungzip(b));
	}  
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章