網站首頁 編程語言 正文
本文主要介紹了Golang使用gzip壓縮字符減少redis等存儲占用的實現,分享給大家,具體如下:
package compression import ( ?? ?"bytes" ?? ?"compress/gzip" ?? ?"encoding/json" ) func GzipEncode(input []byte) ([]byte, error) { ?? ?// 創建一個新的 byte 輸出流 ?? ?var buf bytes.Buffer ?? ?// 創建一個新的 gzip 輸出流 ?? ?//NoCompression ? ? ?= flate.NoCompression ? ? ?// 不壓縮 ?? ?//BestSpeed ? ? ? ? ?= flate.BestSpeed ? ? ? ? ?// 最快速度 ?? ?//BestCompression ? ?= flate.BestCompression ? ?// 最佳壓縮比 ?? ?//DefaultCompression = flate.DefaultCompression // 默認壓縮比 ?? ?//gzip.NewWriterLevel() ?? ?gzipWriter := gzip.NewWriter(&buf) ?? ?// 將 input byte 數組寫入到此輸出流中 ?? ?_, err := gzipWriter.Write(input) ?? ?if err != nil { ?? ??? ?_ = gzipWriter.Close() ?? ??? ?return nil, err ?? ?} ?? ?if err := gzipWriter.Close(); err != nil { ?? ??? ?return nil, err ?? ?} ?? ?// 返回壓縮后的 bytes 數組 ?? ?return buf.Bytes(), nil } func GzipDecode(input []byte) ([]byte, error) { ?? ?// 創建一個新的 gzip.Reader ?? ?bytesReader := bytes.NewReader(input) ?? ?gzipReader, err := gzip.NewReader(bytesReader) ?? ?if err != nil { ?? ??? ?return nil, err ?? ?} ?? ?defer func() { ?? ??? ?// defer 中關閉 gzipReader ?? ??? ?_ = gzipReader.Close() ?? ?}() ?? ?buf := new(bytes.Buffer) ?? ?// 從 Reader 中讀取出數據 ?? ?if _, err := buf.ReadFrom(gzipReader); err != nil { ?? ??? ?return nil, err ?? ?} ?? ?return buf.Bytes(), nil } // 壓縮 func MarshalJsonAndGzip(data interface{}) ([]byte, error) { ?? ?marshalData, err := json.Marshal(data) ?? ?if err != nil { ?? ??? ?return nil, err ?? ?} ?? ?gzipData, err := GzipEncode(marshalData) ?? ?if err != nil { ?? ??? ?return nil, err ?? ?} ?? ?return gzipData, err } // 解壓 func UnmarshalDataFromJsonWithGzip(input []byte, output interface{}) error { ?? ?decodeData, err := GzipDecode(input) ?? ?if err != nil { ?? ??? ?return err ?? ?} ?? ?err = json.Unmarshal(decodeData, output) ?? ?if err != nil { ?? ??? ?return err ?? ?} ?? ?return nil }
原文鏈接:https://blog.csdn.net/yonggeit/article/details/125743336
相關推薦
- 2022-03-04 uniapp和原生app交互
- 2022-06-21 flask上傳作品之dbm操作的實現_python
- 2022-06-29 python人工智能tensorflow函數tf.get_collection使用方法_python
- 2023-06-17 C++中for?auto的用法及說明_C 語言
- 2022-07-02 基于np.arange與np.linspace細微區別(數據溢出問題)_python
- 2022-09-13 C#?wpf使用ListBox實現尺子控件的示例代碼_C#教程
- 2023-09-12 Spring AOP 登錄日志
- 2023-07-02 解密Python中的作用域與名字空間_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支