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

简介

在项目中,存在传递超大 json 数据的场景。直接传输超大 json 数据的话,有以下两个弊端

  • 占用网络带宽,而有些云产品就是按照带宽来计费的,间接浪费了钱
  • 传输数据大导致网络传输耗时较长
    为了避免直接传输超大 json 数据,可以对 json 数据进行 Gzip 压缩后,再进行网络传输。
  • 请求头添加 Content-Encoding 标识,传输的数据进行过压缩
  • Servlet Filter 拦截请求,对压缩过的数据进行解压
  • HttpServletRequestWrapper 包装,把解压的数据写入请求体

pom.xml 引入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>

    <groupid>com.olive</groupid>
    <artifactid>request-uncompression</artifactid>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>request-uncompression</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>2.5.14</version>
        <relativepath> <!-- lookup parent from repository -->
    </relativepath></parent>

    <properties>
        <project.build.sourceencoding>UTF-8</project.build.sourceencoding>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
        <dependency>
            <groupid>com.alibaba.fastjson2</groupid>
            <artifactid>fastjson2</artifactid>
            <version>2.0.14</version>
        </dependency>
    <dependency>
            <groupid>commons-io</groupid>
            <artifactid>commons-io</artifactid>
            <version>2.9.0</version>
        </dependency>
    </dependencies>
</project>

创建压缩工具类

GzipUtils 类提供压缩解压相关方法

package com.olive.utils;

import com.alibaba.fastjson2.JSON;
import com.olive.vo.ArticleRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Slf4j
public class GzipUtils {

    private static final String GZIP_ENCODE_UTF_8 = "UTF-8";

    /**
     * &#x5B57;&#x7B26;&#x4E32;&#x538B;&#x7F29;&#x4E3A;GZIP&#x5B57;&#x8282;&#x6570;&#x7EC4;
     *
     * @param str
     * @return
     */
    public static byte[] compress(String str) {
        return compress(str, GZIP_ENCODE_UTF_8);
    }

    /**
     * &#x5B57;&#x7B26;&#x4E32;&#x538B;&#x7F29;&#x4E3A;GZIP&#x5B57;&#x8282;&#x6570;&#x7EC4;
     *
     * @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 = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
        } catch (IOException e) {
           log.error("compress>>", e);
        }finally {
            if(gzip!=null){
                try {
                    gzip.close();
                } catch (IOException e) {
                }
            }
        }
        return out.toByteArray();
    }

    /**
     * GZIP&#x89E3;&#x538B;&#x7F29;
     *
     * @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);
        GZIPInputStream unGzip = null;
        try {
            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) {
            log.error("uncompress>>", e);
        }finally {
            if(unGzip!=null){
                try {
                    unGzip.close();
                } catch (IOException e) {
                }
            }
        }
        return out.toByteArray();
    }

    /**
     * &#x89E3;&#x538B;&#x5E76;&#x8FD4;&#x56DE;String
     *
     * @param bytes
     * @return
     */
    public static String uncompressToString(byte[] bytes) throws IOException {
        return uncompressToString(bytes, GZIP_ENCODE_UTF_8);
    }

    /**
     * @param bytes
     * @return
     */
    public static byte[] uncompressToByteArray(byte[] bytes) throws IOException {
        return uncompressToByteArray(bytes, GZIP_ENCODE_UTF_8);
    }

    /**
     * &#x89E3;&#x538B;&#x6210;&#x5B57;&#x7B26;&#x4E32;
     *
     * @param bytes    &#x538B;&#x7F29;&#x540E;&#x7684;&#x5B57;&#x8282;&#x6570;&#x7EC4;
     * @param encoding &#x7F16;&#x7801;&#x65B9;&#x5F0F;
     * @return &#x89E3;&#x538B;&#x540E;&#x7684;&#x5B57;&#x7B26;&#x4E32;
     */
    public static String uncompressToString(byte[] bytes, String encoding) throws IOException {
        byte[] result = uncompressToByteArray(bytes, encoding);
        return new String(result);
    }

    /**
     * &#x89E3;&#x538B;&#x6210;&#x5B57;&#x8282;&#x6570;&#x7EC4;
     *
     * @param bytes
     * @param encoding
     * @return
     */
    public static byte[] uncompressToByteArray(byte[] bytes, String encoding) throws IOException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        GZIPInputStream unGzip = null;
        try {
            unGzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = unGzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
            log.error("uncompressToByteArray>>", e);
            throw new IOException("&#x89E3;&#x538B;&#x7F29;&#x5931;&#x8D25;&#xFF01;");
        }finally {
            if(unGzip!=null){
                unGzip.close();
            }
        }
    }

    /**
     * &#x5C06;&#x5B57;&#x8282;&#x6D41;&#x8F6C;&#x6362;&#x6210;&#x6587;&#x4EF6;
     *
     * @param filename
     * @param data
     * @throws Exception
     */
    public static void saveFile(String filename, byte[] data) throws Exception {
        FileOutputStream fos = null;
        try {
            if (data != null) {
                String filepath = "/" + filename;
                File file = new File(filepath);
                if (file.exists()) {
                    file.delete();
                }
                fos = new FileOutputStream(file);
                fos.write(data, 0, data.length);
                fos.flush();
                System.out.println(file);
            }
        }catch (Exception e){
            throw e;
        }finally {
            if(fos!=null){
                fos.close();
            }
        }
    }

}

对Request进行包装

UnZipRequestWrapper 读取输入流,然进行解压;解压完后,再把解压出来的数据封装到输入流中。

package com.olive.filter;

import com.olive.utils.GzipUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 *  Json String &#x7ECF;&#x8FC7;&#x538B;&#x7F29;&#x540E;&#x4FDD;&#x5B58;&#x4E3A;&#x4E8C;&#x8FDB;&#x5236;&#x6587;&#x4EF6; -> &#x89E3;&#x538B;&#x7F29;&#x540E;&#x8FD8;&#x539F;&#x6210; Jso nString&#x8F6C;&#x6362;&#x6210;byte[]&#x5199;&#x56DE;body&#x4E2D;
 */
@Slf4j
public class UnZipRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] bytes;

    public UnZipRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        try (BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            final byte[] body;
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            body = baos.toByteArray();
            if (body.length == 0) {
                log.info("Body&#x65E0;&#x5185;&#x5BB9;&#xFF0C;&#x65E0;&#x9700;&#x89E3;&#x538B;");
                bytes = body;
                return;
            }
            this.bytes = GzipUtils.uncompressToByteArray(body);
        } catch (IOException ex) {
            log.error("&#x89E3;&#x538B;&#x7F29;&#x6B65;&#x9AA4;&#x53D1;&#x751F;&#x5F02;&#x5E38;&#xFF01;", ex);
            throw ex;
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

}

定义GzipFilter对请求进行拦截

GzipFilter 拦截器根据请求头是否包含 Content-Encoding=application/gzip,如果包含就对数据进行解压;否则就直接放过。

package com.olive.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * &#x89E3;&#x538B;filter
 */
@Slf4j
@Component
public class GzipFilter implements Filter {

    private static final String CONTENT_ENCODING = "Content-Encoding";

    private static final String CONTENT_ENCODING_TYPE = "application/gzip";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init GzipFilter");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String encodeType = httpServletRequest.getHeader(CONTENT_ENCODING);
        if (encodeType!=null && CONTENT_ENCODING_TYPE.equals(encodeType)) {
            log.info("&#x8BF7;&#x6C42;:{} &#x9700;&#x8981;&#x89E3;&#x538B;", httpServletRequest.getRequestURI());
            UnZipRequestWrapper unZipRequest = new UnZipRequestWrapper(httpServletRequest);
            chain.doFilter(unZipRequest, response);
        }else {
            log.info("&#x8BF7;&#x6C42;:{} &#x65E0;&#x9700;&#x89E3;&#x538B;", httpServletRequest.getRequestURI());
            chain.doFilter(request,response);
        }
        log.info("&#x8017;&#x65F6;&#xFF1A;{}ms", System.currentTimeMillis() - start);
    }

    @Override
    public void destroy() {
        log.info("destroy GzipFilter");
    }
}

注册 GzipFilter 拦截器

package com.olive.config;

import com.olive.filter.GzipFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * &#x6CE8;&#x518C;filter
 */
@Configuration
public class FilterRegistration {

    @Autowired
    private GzipFilter gzipFilter;

    @Bean
    public FilterRegistrationBean<gzipfilter> gzipFilterRegistrationBean() {
        FilterRegistrationBean<gzipfilter> registration = new FilterRegistrationBean<>();
        //Filter&#x53EF;&#x4EE5;new&#xFF0C;&#x4E5F;&#x53EF;&#x4EE5;&#x4F7F;&#x7528;&#x4F9D;&#x8D56;&#x6CE8;&#x5165;Bean
        registration.setFilter(gzipFilter);
        //&#x8FC7;&#x6EE4;&#x5668;&#x540D;&#x79F0;
        registration.setName("gzipFilter");
        //&#x62E6;&#x622A;&#x8DEF;&#x5F84;
        registration.addUrlPatterns("/*");
        //&#x8BBE;&#x7F6E;&#x987A;&#x5E8F;
        registration.setOrder(1);
        return registration;
    }
}
</gzipfilter></gzipfilter>

定义 Controller

该 Controller 非常简单,主要是输入请求的数据

package com.olive.controller;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson2.JSON;
import com.olive.vo.ArticleRequestVO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RequestMapping("/getArticle")
    public Map<string, object> getArticle(@RequestBody ArticleRequestVO articleRequestVO){
        Map<string, object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        System.out.println(JSON.toJSONString(articleRequestVO));
        return result;
    }

}
</string,></string,>

Controller 参数接收VO

package com.olive.vo;

import lombok.Data;

import java.io.Serializable;

@Data
public 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;

@SpringBootApplication
public 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&#x4E50;&#x56ED;",
    "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&#x5F04;&#x6F6E;&#x513F;");
      try {
          byte[] bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\2230\\Desktop\\&#x51EF;&#x5E73;&#x9879;&#x76EE;&#x8D44;&#x6599;\\&#x6539;&#x88C5;&#x8F66;&#x9879;&#x76EE;\\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 对象

Original: https://www.cnblogs.com/happyhuangjinjin/p/16759500.html
Author: BUG弄潮儿
Title: Springboot 之 Filter 实现 Gzip 压缩超大 json 对象

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/801312/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球