Springboot 之 Filter 实现 Gzip 压缩超大 json 对象( 三 )

package com.olive.vo;import lombok.Data;import java.io.Serializable;@Datapublic class ArticleRequestVO implements Serializable {private Long id;private String title;private String content;}定义 Springboot 引导类package com.olive;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class);}}测试

  • 非压缩请求测试
curl -X POST \http://127.0.0.1:8080/getArticle \-H 'content-type: application/json' \-d '{ "id":1, "title": "java乐园", "content":"xxxxxxxxxx"}'
  • 压缩请求测试

Springboot 之 Filter 实现 Gzip 压缩超大 json 对象

文章插图

Springboot 之 Filter 实现 Gzip 压缩超大 json 对象

文章插图
不要直接将压缩后的 byte[] 数组当作字符串进行传输 , 否则压缩后的请求数据比没压缩后的还要大得多!项目中一般采用以下两种传输压缩后的 byte[] 的方式:
  • 将压缩后的 byet[] 进行 Base64 编码再传输字符串,这种方式会损失掉一部分 GZIP 的压缩效果,适用于压缩结果要存储在 Redis 中的情况
  • 将压缩后的 byte[] 以二进制的形式写入到文件中 , 请求时直接在 body 中带上文件即可,用这种方式可以不损失压缩效果
小编测试采用第二种方式,采用以下代码把原始数据进行压缩
public static void main(String[] args) {ArticleRequestVO vo = new ArticleRequestVO();vo.setId(1L);vo.setTitle("bug弄潮儿");try {byte[] bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\2230\\Desktop\\凯平项目资料\\改装车项目\\CXSSBOOT_DB_DDL-1.0.9.sql"));vo.setContent(new String(bytes));byte[] dataBytes = compress(JSON.toJSONString(vo));saveFile("d:/vo.txt", dataBytes);} catch (Exception e) {e.printStackTrace();}}压缩后数据存储到d:/vo.txt,然后在 postman 中安装下图选择
Springboot 之 Filter 实现 Gzip 压缩超大 json 对象

文章插图
【Springboot 之 Filter 实现 Gzip 压缩超大 json 对象】

推荐阅读