1. 程式人生 > >SpringBoot專案開發(二十一):Gzip壓縮

SpringBoot專案開發(二十一):Gzip壓縮

為了減少資料在網路中的傳輸量,從而減少傳輸時長,增加使用者體驗,瀏覽器大都是支援Gzip壓縮技術的,http的請求頭 Accept-Encoding:gzip, deflate 就表示這次請求可以接受Gzip壓縮後的資料,圖片不要進行壓縮,因為圖片完全可以在專案開發中使用壓縮後的圖片。壓縮會有一定的CPU效能損耗。

下面介紹幾種 Gzip壓縮方式

1.SpringBoot開啟Gzip壓縮

在application.properties中加入如下配置:

server.compression.enabled=true
server.compression.mime-types=application
/javascript,text/css,application/json,application/xml,text/html,text/xml,text/plain

壓縮前:25.3kb,50.0kb,37.5kb,5.1kb,34.7kb
這裡寫圖片描述
壓縮後:6.4kb,11.7kb,8.3kb,1.3kb,34.7kb
這裡寫圖片描述
壓縮後可看到檔案有4倍左右的差距,能大大減少網路傳輸量,頁面載入速度加快

2.Tomcat開啟Gzip壓縮

tomcat中使用gzip需要進行配置,在server.xml中,在Connector標籤中加入如下屬性

compression="on" 
compressionMinSize="2048"
compressableMimeType="text/html,text/css,text/javascript"
3.Nginx開啟Gzip壓縮
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
#gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary off;

過載nginx即可
第1行:開啟Gzip
第2行:不壓縮臨界值,大於1K的才壓縮,一般不用改
第3行:buffer,不用改
第4行:用了反向代理的話,末端通訊是HTTP/1.0,有需求的應該也不用看我這科普文了;有這句的話註釋了就行了,預設是HTTP/1.1
第5行:壓縮級別,1-10,數字越大壓縮的越好,時間也越長,看心情隨便改吧
第6行:進行壓縮的檔案型別,缺啥補啥就行了,JavaScript有兩種寫法,最好都寫上吧,總有人抱怨js檔案沒有壓縮,其實多寫一種格式就行了
第7行:跟Squid等快取服務有關,on的話會在Header裡增加”Vary: Accept-Encoding”,我不需要這玩意,自己對照情況看著辦吧

4.GZIPOutputStream,GZIPInputStream壓縮與解壓
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.StringUtils;

public class GZIPUtils {

    public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
    public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";

    /**
     * 字串壓縮為GZIP位元組陣列
     * @param str
     * @return
     */
    public static byte[] compress(String str) {
        return compress(str, GZIP_ENCODE_UTF_8);
    }

    /**
     * 字串壓縮為GZIP位元組陣列
     * @param str
     * @param encoding
     * @return
     */
    public static byte[] compress(String str, String encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    /**
     * GZIP解壓縮
     * @param bytes
     * @return
     */
    public static byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    /**
     * 解壓並返回String
     * @param bytes
     * @return
     */
    public static String uncompressToString(byte[] bytes) {
        return uncompressToString(bytes, GZIP_ENCODE_UTF_8);
    }

    /**
     * 解壓
     * @param bytes
     * @param encoding
     * @return
     */
    public static String uncompressToString(byte[] bytes, String encoding) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(encoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String str = "%5B%7B%22lastUpdateTime%22%3A%222011-10-28+9%3A39%3A41%22%2C%22smsList%22%3A%5B%7B%22liveState%22%3A%221";
        System.out.println("原長度:" + str.length());
        System.out.println("壓縮後字串:" + GZIPUtils.compress(str).toString().length());
        System.out.println("解壓縮後字串:" + StringUtils.newStringUtf8(GZIPUtils.uncompress(GZIPUtils.compress(str))));
        System.out.println("解壓縮後字串:" + GZIPUtils.uncompressToString(GZIPUtils.compress(str)));
    }
}