文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Springboot 中的 Filter 实现超大响应 JSON 数据压缩的方法

2022-11-13 18:19

关注

简介

项目中,请求时发送超大 json 数据外;响应时也有可能返回超大 json数据。上一篇实现了请求数据的 gzip 压缩。本篇通过 filter 实现对响应 json 数据的压缩。
先了解一下以下两个概念:

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>response-compression</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
 
	<name>response-compression</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 -->
	</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>

对Response进行包装

GzipResponseWrapper 类重新定义了输出流,拦截需要输出的数据,直接缓存到 ByteArrayOutputStream 中。

package com.olive.filter;
 
import lombok.extern.slf4j.Slf4j;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
 
@Slf4j
public class GzipResponseWrapper extends HttpServletResponseWrapper {
 
    
    private ByteArrayOutputStream buffer;
 
    
    private GzipResponseWrapper.CustomServletOutputStream servletOutputStream;
 
    
    private PrintWriter writer;
 
    public GzipResponseWrapper(HttpServletResponse response) {
        super(response);
        //original HttpServletResponse object
        buffer = new ByteArrayOutputStream();
        servletOutputStream = new GzipResponseWrapper.CustomServletOutputStream(buffer);
        try {
            writer = new PrintWriter(new OutputStreamWriter(buffer, response.getCharacterEncoding()), true);
        } catch (UnsupportedEncodingException e) {
            log.error("GZipHttpServletResponse", e);
        }
    }
 
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return servletOutputStream;
    }
 
    @Override
    public PrintWriter getWriter() throws IOException {
        return writer;
    }
 
    @Override
    public void flushBuffer() throws IOException {
        if (servletOutputStream != null) {
            servletOutputStream.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }
 
    
    public byte[] getOutputData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }
 
    private static class CustomServletOutputStream extends ServletOutputStream {
 
        
        private ByteArrayOutputStream buffer;
 
        public CustomServletOutputStream(ByteArrayOutputStream buffer) {
            this.buffer = buffer;
        }
 
        @Override
        public boolean isReady() {
            return true;
        }
 
        @Override
        public void setWriteListener(WriteListener listener) {
        }
 
        
        @Override
        public void write(int b) throws IOException {
            buffer.write(b);
        }
    }
}

定义GzipFilter对输出进行拦截

GzipFilter 拦截器获取缓存的需要输出的数据,进行压缩,在输出数据之前先设置响应头Content-Encoding : gzip

package com.olive.filter;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.GZIPOutputStream;
 

@Slf4j
public class GzipFilter implements Filter {
 
    private final String GZIP = "gzip";
 
    public void destroy() {
        log.info("GzipFilter destroy");
    }
 
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        log.info("GzipFilter start");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String acceptEncoding = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
        //searching for 'gzip' in ACCEPT_ENCODING header
        if( acceptEncoding != null && acceptEncoding.indexOf(GZIP) >= 0){
            GzipResponseWrapper gzipResponseWrapper = new GzipResponseWrapper(response);
            //pass the customized response object to controller to capture the output data
            chain.doFilter(request, gzipResponseWrapper);
            //get captured data
            byte[] data = gzipResponseWrapper.getOutputData();
            log.info("截获到数据:" + data.length + " bytes");
            //get gzip data
            ByteArrayOutputStream gzipBuffer = new ByteArrayOutputStream();
            GZIPOutputStream gzipOut = new GZIPOutputStream(gzipBuffer);
            gzipOut.write(data);
            gzipOut.flush();
            gzipOut.close();
            byte[] gzipData = gzipBuffer.toByteArray();
            log.info("压缩后数据:" + gzipData.length + " bytes");
            //set response header and output
            response.setHeader(HttpHeaders.CONTENT_ENCODING, GZIP);
            response.getOutputStream().write(gzipData);
            response.getOutputStream().flush();
        }else{
            chain.doFilter(req, resp);
        }
    }
 
    public void init(FilterConfig config) throws ServletException {
        log.info("GzipFilter init");
    }
 
}

注册 GzipFilter 拦截器

package com.olive.config;
 
import com.olive.filter.GzipFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 

@Configuration
public class FilterRegistration {
 
    @Bean
    public FilterRegistrationBean<GzipFilter> gzipFilterRegistrationBean() {
        FilterRegistrationBean<GzipFilter> registration = new FilterRegistrationBean<>();
        //Filter可以new,也可以使用依赖注入Bean
        registration.setFilter(new GzipFilter());
        //过滤器名称
        registration.setName("gzipFilter");
        //拦截路径
        registration.addUrlPatterns("/*");
        //设置顺序
        registration.setOrder(1);
        return registration;
    }
}

定义 Controller

该 Controller 非常简单,主要读取一个大文本文件,作为输出的内容。

package com.olive.controller;
 
import java.io.File;
import java.util.HashMap;
import java.util.Map;
 
import com.olive.vo.ArticleRequestVO;
import org.apache.commons.io.FileUtils;
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(){
		Map<String, Object> result = new HashMap<>();
		result.put("code", 200);
		result.put("msg", "success");
		byte[] bytes = null;
		try {
			bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\2230\\Desktop\\凯平项目资料\\改装车项目\\CXSSBOOT_DB_DDL-1.0.9.sql"));
		}catch (Exception e){
 
		}
		String content = new String(bytes);
		ArticleRequestVO vo = new ArticleRequestVO();
		vo.setId(1L);
		vo.setTitle("BUG弄潮儿");
		vo.setContent(content);
		result.put("body", vo);
		return result;
	}
 
}

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

curl -X POST http://127.0.0.1:8080/getArticle 

到此这篇关于Springboot 中的 Filter 实现超大响应 JSON 数据压缩的文章就介绍到这了,更多相关Springboot JSON 数据压缩内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯