springboot集成gzip和zip數據壓縮傳輸-滿足2k數據自動壓縮(適用大數據信息傳輸)

文章目錄

    • 1)、springboot的gzip壓縮-滿足2k數據自動壓縮
        • 1.1后端壓縮
        • 1.2前端解壓
        • 1.3 滿足最小響應大小(2KB)和指定MIME類型的響應進行GZIP壓縮
          • yml配置
          • 自定義配置或者使用Java配置
    • 2)、gzip壓縮
        • 1.1接口使用-數據壓縮發送前端
        • 1.2 接口使用-數據解壓來自前端來的壓縮數據
        • 1.3 GzipUtils工具類
    • 3)、前端壓縮數據
        • 1.2 實現GzipUtils類
        • 1.3 前端使用示例
    • 4)、zip壓縮方案
        • 接口使用-數據壓縮發送前端
        • 接口使用-數據解壓來自前端來的壓縮數據
        • ZipUtils工具類

1)、springboot的gzip壓縮-滿足2k數據自動壓縮

1.1后端壓縮
 @GetMapping(value = "/data", produces = "application/json")public void getData(HttpServletResponse response) throws IOException {String data = "your large data here"; // Replace with actual large dataresponse.setHeader("Content-Encoding", "gzip");response.setContentType("application/json");try (OutputStream os = response.getOutputStream();GZIPOutputStream gzipOutputStream = new GZIPOutputStream(os)) {gzipOutputStream.write(data.getBytes());}}
1.2前端解壓
fetch('/api/data', {headers: {'Accept-Encoding': 'gzip'}
})
.then(response => {if (response.ok) {return response.blob();}throw new Error('Network response was not ok.');
})
.then(blob => {const reader = new FileReader();reader.onload = () => {const decompressedData = pako.inflate(reader.result, { to: 'string' });console.log(JSON.parse(decompressedData));};reader.readAsArrayBuffer(blob);
})
.catch(error => {console.error('There was a problem with your fetch operation:', error);
});
1.3 滿足最小響應大小(2KB)和指定MIME類型的響應進行GZIP壓縮

將為JSON、XML、文本和JavaScript以及CSS等類型的響應啟用GZIP壓縮,并且響應大小至少需要2KB才會被壓縮

yml配置
# application.yml
server:compression:enabled: truemime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/cssmin-response-size: 2048
自定義配置或者使用Java配置

創建了一個ShallowEtagHeaderFilter bean和一個GzipCompressingFilter bean,后者會對滿足最小響應大小(2KB)和指定MIME類型的響應進行GZIP壓縮

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.filter.ShallowEtagHeaderFilter;import java.util.Arrays;
import java.util.List;@Configuration
public class GzipConfig {@Beanpublic ShallowEtagHeaderFilter shallowEtagHeaderFilter() {return new ShallowEtagHeaderFilter();}@Beanpublic GzipCompressingFilter gzipCompressingFilter() {GzipCompressingFilter filter = new GzipCompressingFilter();filter.setMinGzipSize(2048);List<String> mimeTypes = Arrays.asList("text/html", "text/xml", "text/plain", "text/css", "application/javascript", "application/json", "application/xml");filter.setMimeTypes(mimeTypes);return filter;}
}

2)、gzip壓縮

1.1接口使用-數據壓縮發送前端
    @Autowiredprivate GzipUtils gzipUtils;@RequestMapping(value = "testGzip", method = RequestMethod.POST)public JSONBeansResponse testGzip(@RequestBody Map<String, String> map) throws IOException {if (null != map) {String sqlStr = map.get("paramStr");// 調用數據庫獲取數據Map<String, Object> resMap = testMapper.findInfo(sqlStr);String dataStr = JSONObject.toJSONString(resMap);// 開始壓縮數據byte[] compress1 = gzipUtils.compress(dataStr);String FileBuf = Base64.getEncoder().encodeToString(compress1);return new JSONBeansResponse<>(FileBuf);}return new JSONBeansResponse<>(new ArrayList<>(0));}
1.2 接口使用-數據解壓來自前端來的壓縮數據
    @RequestMapping(value = "testUnGzip", method = RequestMethod.POST)public JSONBeansResponse testUnGzip(@RequestBody Map<String, String> map) throws IOException {if (null != map) {String dataStream = map.get("dataStream ");byte[] decode = Base64.getDecoder().decode(dataStream);byte[] compress1 = gzipUtils.uncompress(decode);String dataStr = new String(compress1);Map<String, Object> res = JSONObject.parseObject(dataStr, Map.class);return new JSONBeansResponse<>(res);}return new JSONBeansResponse<>(new ArrayList<>(0));}

遇到問題
解壓時候報錯:java.util.zip.ZipException: Not in GZIP format
解決方案:在轉換為字符串時,一定要使用ISO-8859-1這樣的單字節編碼

 public R getLikeKeys(HttpServletRequest request, HttpServletResponse response, String data){String data = "xxxxxxxx"; // 前端傳來的數據String data3=new String(data.getBytes(), StandardCharsets.ISO_8859_1);}
1.3 GzipUtils工具類
package com.自己的包.util;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/*** @program: tool_java* @description:* @author: sfp* @create: 2021-11-30 14:33**/
@Component
public class GzipUtils {/*** 壓縮** @param data 數據流* @return 壓縮數據流* @throws IOException 異常*/public byte[] compress(byte[] data) throws IOException {if (data == null || data.length == 0) {return null;}ByteArrayOutputStream out = new ByteArrayOutputStream();GZIPOutputStream gzip = new GZIPOutputStream(out);gzip.write(data);gzip.close();return out.toByteArray();}/*** 壓縮** @param str 需要壓縮數據信息* @return 壓縮數據流* @throws IOException 異常*/public byte[] compress(String str) throws IOException {if (str == null || str.length() == 0) {return null;}return compress(str.getBytes(StandardCharsets.UTF_8));}/*** 解壓** @param data 欲解壓數據流* @return 原數據流* @throws IOException 異常*/public byte[] uncompress(byte[] data) throws IOException {if (data == null || data.length == 0) {return data;}ByteArrayOutputStream out = new ByteArrayOutputStream();ByteArrayInputStream in = new ByteArrayInputStream(data);GZIPInputStream gunzip = new GZIPInputStream(in);byte[] buffer = new byte[1024];int n;while ((n = gunzip.read(buffer)) >= 0) {out.write(buffer, 0, n);}gunzip.close();in.close();return out.toByteArray();}/*** 解壓** @param str 欲解壓數據字符串* @return 原數據* @throws IOException 異常*/public String uncompress(String str) throws IOException {if (str == null || str.length() == 0) {return str;}byte[] data = uncompress(str.getBytes(StandardCharsets.ISO_8859_1));return new String(data);}
}

3)、前端壓縮數據

引入pako庫
首先,通過npm安裝pako庫:
npm install pako
如果你不使用npm,也可以通過CDN引入pako庫:
<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.0.4/pako.min.js"></script>

1.2 實現GzipUtils類

然后,在JavaScript中實現GzipUtils類:

class GzipUtils {/*** 壓縮** @param {Uint8Array|ArrayBuffer} data 數據流* @return {Uint8Array} 壓縮數據流*/static compress(data) {if (!data || data.length === 0) {return null;}return pako.gzip(data);}/*** 壓縮** @param {string} str 需要壓縮數據信息* @return {Uint8Array} 壓縮數據流*/static compressString(str) {if (!str || str.length === 0) {return null;}const utf8Data = new TextEncoder().encode(str);return this.compress(utf8Data);}/*** 解壓** @param {Uint8Array|ArrayBuffer} data 欲解壓數據流* @return {Uint8Array} 原數據流*/static uncompress(data) {if (!data || data.length === 0) {return data;}return pako.ungzip(data);}/*** 解壓** @param {string} str 欲解壓數據字符串* @return {string} 原數據*/static uncompressString(str) {if (!str || str.length === 0) {return str;}const compressedData = new Uint8Array([...str].map(char => char.charCodeAt(0)));const uncompressedData = this.uncompress(compressedData);return new TextDecoder().decode(uncompressedData);}
}
1.3 前端使用示例
// 使用pako庫,確保pako庫已引入
// npm install pako
// 或者通過CDN引入 pako.min.js// 壓縮字符串
const originalString = "Hello, this is a string to be compressed.";
const compressedData = GzipUtils.compressString(originalString);
console.log("Compressed Data:", compressedData);// 解壓字符串
const decompressedString = GzipUtils.uncompressString(compressedData);
console.log("Decompressed String:", decompressedString);// 確保解壓后的字符串與原始字符串相同
console.assert(originalString === decompressedString, "Strings do not match!");

4)、zip壓縮方案

接口使用-數據壓縮發送前端
    @Autowiredprivate ZipUtils zipUtils;@RequestMapping(value = "testzip", method = RequestMethod.POST)public JSONBeansResponse testzip(@RequestBody Map<String, String> map) throws IOException {String sqlStr = map.get("paramStr");List<Map<String, Object>> resMap = testMapper.findInfo(sqlStr);;String dataStr = JSONObject.toJSONString(resMap);// 開始壓縮數據byte[] compress1 = zipUtils.compress(dataStr);String FileBuf = Base64.getEncoder().encodeToString(compress1);// 開始解壓數據String s = zipUtils.uncompress(FileBuf);List<Map> arrayLists = JSONObject.parseArray(s, Map.class);return new JSONBeansResponse<>(arrayLists);}
接口使用-數據解壓來自前端來的壓縮數據
ZipUtils工具類
package com.自己的包.util;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* @program: tool_java
* @description: zip壓縮工具
* @author: sfp
* @create: 2021-12-01 14:11
**/
@Component
public class ZipUtils {
/** 壓縮* @param data  原數據流* @return 壓縮后的數據流* @throws IOException 異常*/public byte[] compress(byte[] data) throws IOException {if (data == null || data.length == 0) {return null;}ByteArrayOutputStream out = new ByteArrayOutputStream();ZipOutputStream gzip = new ZipOutputStream(out);gzip.putNextEntry(new ZipEntry("json"));gzip.write(data);gzip.close();return out.toByteArray();}/** 壓縮* @param str  原數據字符串* @return 壓縮后的數據流* @throws IOException 異常*/public byte[] compress(String str) throws IOException {if (str == null || str.length() == 0) {return null;}return compress(str.getBytes(StandardCharsets.UTF_8));}/** 解壓縮* @param data  壓縮后的數據流* @return 原數據的數據流* @throws IOException 異常*/public byte[] uncompress(byte[] data) throws IOException {if (data == null || data.length == 0) {return data;}ByteArrayOutputStream out = new ByteArrayOutputStream();ByteArrayInputStream in = new ByteArrayInputStream(data);ZipInputStream gunzip = new ZipInputStream(in);ZipEntry nextEntry = gunzip.getNextEntry();while (nextEntry != null) {final String fileName = nextEntry.getName();if (nextEntry.isDirectory()) {nextEntry = gunzip.getNextEntry();} else if (fileName.equals("json")) {byte[] buffer = new byte[1024];int n;while ((n = gunzip.read(buffer)) >= 0) {out.write(buffer, 0, n);}gunzip.close();in.close();return out.toByteArray();}}return out.toByteArray();}/** 解壓* @param str  壓縮后的base64流* @return 原數據字符串* @throws IOException 異常*/public String uncompress(String str) throws IOException {if (str == null || str.length() == 0) {return str;}byte[] data = uncompress(Base64.getDecoder().decode(str));return new String(data);}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/41626.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/41626.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/41626.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java面試題系列 - 第3天

題目&#xff1a;Java集合框架詳解與高效使用策略 背景說明&#xff1a;Java集合框架是Java標準庫的重要組成部分&#xff0c;提供了一系列容器類&#xff0c;如List、Set、Map等&#xff0c;用于存儲和操作集合數據。熟練掌握集合框架的使用&#xff0c;對于編寫高效、健壯的…

機器學習之神經網絡

簡介 神經網絡(Neural Network)是一種模仿人類大腦的機器學習算法,由一系列相互連接的神經元組成。它能夠自動學習數據的特征和規律,并對新的輸入數據進行預測和分類。 神經網絡作為一種模仿生物大腦機制的機器學習算法,其產生和發展主要源于以下幾個方面的背景: 對人腦認知…

第11章 規劃過程組(二)(11.8排列活動順序)

第11章 規劃過程組&#xff08;二&#xff09;11.8排列活動順序&#xff0c;在第三版教材第390~391頁&#xff1b; 文字圖片音頻方式 第一個知識點&#xff1a;主要工具與技術&#xff08;重要知識點&#xff09; 1、箭線圖法(ADM) &#xff08;雙代號網絡圖或活動箭線圖&am…

template配置項詳情——03

<body> // vue.config是vue全局配置對象 // productionTip 屬性可能設置是否生產提示信息 //默認值是&#xff1a;true,如果是false 則表示組織生產提示信息 vue.congfig.productionTip false //指定掛載位置 //注意&#xff1a;以下代碼只有vue框架能夠看懂的代碼。…

windows USB 設備驅動開發- 不同模型下的控制傳輸

在不同的模型下&#xff0c;USB控制傳輸會有不同的特點&#xff0c;但是任何控制傳輸的目標都始終是默認端點。 接收者是設備的實體&#xff0c;其信息&#xff08;描述符、狀態等&#xff09;是主機感興趣的。請求可進一步分為&#xff1a;配置請求、功能請求和狀態請求。 發…

leetcode力扣_雙指針問題

141. 環形鏈表 思路&#xff1a;判斷鏈表中是否有環是經典的算法問題之一。常見的解決方案有多種&#xff0c;其中最經典、有效的一種方法是使用 快慢指針&#xff08;Floyd’s Cycle-Finding Algorithm&#xff09;。 初始化兩個指針&#xff1a;一個快指針&#xff08;fast&…

uni-app 使用Pinia進行全局狀態管理并持久化數據

1.引言 最近在學習移動端的開發&#xff0c;使用uni-app前端應用框架&#xff0c;通過學習B站的視頻以及找了一個開發模板&#xff0c;終于是有了一些心得體會。 B站視頻1&#xff1a;Day1-01-uni-app小兔鮮兒導學視頻_嗶哩嗶哩_bilibili B站視頻2&#xff1a;01-課程和uni的…

JavaScript——for in類型

目錄 任務描述 相關知識 for in型 編程要求 任務描述 蘋果apple有多個屬性表示它的產地&#xff0c;比如locationProvince表示省份&#xff0c;這些屬性都以location開頭&#xff0c;和產地無關的屬性都不以location開頭。 本關任務&#xff1a;完成一個計算蘋果產地的函數…

[FFmpeg] windows下安裝帶gpu加速的ffmpeg

1.顯卡能力排查 目前只有 NIVIDIA 支持 ffmpeg 的 gpu加速(AMD貌似也陸續開始支持)。 在下述網站中查找自己的顯卡能夠支持的編解碼格式。https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-newhttps://developer.nvidia.com/video-encode-and-decod…

Vue88-Vuex中的mapActions、mapMutations

一、mapMutations的調用 此時結果不對&#xff0c;因為&#xff1a;若是點擊事件不傳值&#xff0c;默認傳的是event&#xff01;&#xff0c;所以&#xff0c;修改如下&#xff1a; 解決方式1&#xff1a; 解決方式2&#xff1a; 不推薦&#xff0c;寫法麻煩&#xff01; 1-…

【Unity數據交互】二進制私

&#x1f468;?&#x1f4bb;個人主頁&#xff1a;元宇宙-秩沅 &#x1f468;?&#x1f4bb; hallo 歡迎 點贊&#x1f44d; 收藏? 留言&#x1f4dd; 加關注?! &#x1f468;?&#x1f4bb; 本文由 秩沅 原創 &#x1f468;?&#x1f4bb; 專欄交流&#x1f9e7;&…

Bootstrap 5 小工具

Bootstrap 5 小工具 Bootstrap 5 是一個流行的前端框架,它提供了一系列的工具和組件,幫助開發者快速構建響應式和移動優先的網頁。在本文中,我們將探討 Bootstrap 5 中的一些實用小工具,這些工具可以極大地提高開發效率和用戶體驗。 1. 網格系統 Bootstrap 5 的網格系統…

Laravel 宏指令(Macro)動態添加自定義方法到Laravel的核心組件中

Laravel 宏指令&#xff08;Macro&#xff09; 在Laravel中&#xff0c;宏指令&#xff08;Macro&#xff09;是一種靈活的方式&#xff0c;允許您動態添加自定義方法到Laravel的核心組件中&#xff0c;如模型、查詢構建器、集合等&#xff0c;以便在不改變核心代碼的情況下擴展…

電腦硬盤分區的基本步驟(2個實用的硬盤分區方法)

在現代計算機中&#xff0c;硬盤分區是非常重要的一步。無論是新硬盤的初始化&#xff0c;還是重新組織現有硬盤&#xff0c;分區都是必不可少的操作。本文將詳細介紹電腦硬盤分區的基本步驟&#xff0c;幫助您更好地管理和利用硬盤空間。 文章開始&#xff0c;我們先簡單說一…

【C++】 解決 C++ 語言報錯:Invalid Conversion from ‘const char*’ to ‘char*’

文章目錄 引言 在 C 編程中&#xff0c;類型轉換錯誤&#xff08;Invalid Conversion&#xff09;是常見的編譯錯誤之一。特別是當程序試圖將一個常量字符指針&#xff08;const char*&#xff09;轉換為非常量字符指針&#xff08;char*&#xff09;時&#xff0c;會導致編譯…

Vmware環境下ESXi主機 配置上行鏈路、虛擬交換機、端口組、VMkernel網卡

一、適用場景 1、使用專業服務器跑多種不同的業務&#xff0c;每種業務可能所需運行的server環境不同&#xff0c;有的需要Linux server CentOS7/8、kali、unbuntu……有的需要windows server2008、2003、2016、2019、2022…… 2、本例采用的是VMware ESXi6.7 update 3版本&am…

力扣習題--找不同

目錄 前言 題目和解析 1、找不同 2、 思路和解析 總結 前言 本系列的所有習題均來自于力扣網站LeetBook - 力扣&#xff08;LeetCode&#xff09;全球極客摯愛的技術成長平臺 題目和解析 1、找不同 給定兩個字符串 s 和 t &#xff0c;它們只包含小寫字母。 字符串 t…

Java Maven中自動代碼檢查插件詳細介紹

文章目錄 Checkstyle主要特點使用場景配置與使用checkstyle.xmlsuppressions.xml 驗證打包時驗證執行命令驗證 Spotless配置文件內容Java配置部分POM 配置部分Markdown 配置部分Up to Date Checking執行部分 驗證打包時驗證在插件中執行命令驗證 Checkstyle Spotless 結合chec…

ABAP中BAPI_CURRENCY_CONV_TO_INTERNAL 函數的使用方法

在ABAP中&#xff0c;BAPI_CURRENCY_CONV_TO_INTERNAL 函數模塊主要用于將外部金額轉換為內部存儲格式。這對于確保金額數據在SAP系統中的一致性和準確性至關重要。以下是關于該函數模塊使用方法的詳細解釋&#xff1a; 函數模塊參數 調用 BAPI_CURRENCY_CONV_TO_INTERNAL 時…

redis學習(005 java客戶端 RedisTemplate學習)

黑馬程序員Redis入門到實戰教程&#xff0c;深度透析redis底層原理redis分布式鎖企業解決方案黑馬點評實戰項目 總時長 42:48:00 共175P 此文章包含第16p-第p23的內容 文章目錄 java客戶端jedisSpringDataRedis項目實現hash哈希操作 java客戶端 jedis 測試 ps:如果連接不上&…