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

定义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;* 解压filter@Slf4j@Componentpublic class GzipFilter implements Filter {private static final String CONTENT_ENCODING = "Content-Encoding";private static final String CONTENT_ENCODING_TYPE = "application/gzip";@Overridepublic void init(FilterConfig filterConfig) throws ServletException {log.info("init GzipFilter");@Overridepublic 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("请求:{} 需要解压", httpServletRequest.getRequestURI());UnZipRequestWrapper unZipRequest = new UnZipRequestWrapper(httpServletRequest);chain.doFilter(unZipRequest, response);}else {log.info("请求:{} 无需解压", httpServletRequest.getRequestURI());chain.doFilter(request,response);log.info("耗时:{}ms", System.currentTimeMillis() - start);@Overridepublic 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;* 注册filter@Configurationpublic class FilterRegistration {@Autowiredprivate GzipFilter gzipFilter;@Beanpublic FilterRegistrationBean gzipFilterRegistrationBean() {FilterRegistrationBean registration = new FilterRegistrationBean<>();//Filter可以new,也可以使用依赖注入Beanregistration.setFilter(gzipFilter);//过滤器名称registration.setName("gzipFilter");//拦截路径registration.addUrlPatterns("/*");//设置顺序registration.setOrder(1);return registration;定义 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;@RestControllerpublic class TestController {@RequestMapping("/getArticle")public Map getArticle(@RequestBody ArticleRequestVO articleRequestVO){Map result = new HashMap<>();result.put("code", 200);result.put("msg", "success");System.out.println(JSON.toJSONString(articleRequestVO));return result;
Controller 参数接收VO
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' "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();


推荐阅读