优秀的编程知识分享平台

网站首页 > 技术文章 正文

SpringBoot 接口数据压缩 gzip springboot解压zip

nanyue 2024-12-25 14:42:31 技术文章 4 ℃

前言

在开发项目时,压缩响应体数据包大小也是我们常用的优化手段之一。如果响应体过大,会浪费网络流量,增加接口延迟。

SpringBoot支持gzip压缩,并且支持自动压缩,即响应内容长度较短时不压缩,保证响应速度,响应内容长度较长时压缩,减轻带宽压力,配置极其简单。

HTTP响应的gzip压缩

当服务端对响应做了gzip压缩后,header里会添加:Content-Encoding: gzip用于表明返回结果做了gzip压缩。如果客户端不希望该次请求会被压缩,则可以修改请求的header中的Accept-Encoding,去掉gzip即可

springboot配置

springboot压缩配置如下:

server:
  port: 8081
  compression: #开启gzip压缩,返回内容大于2k的才会进行压缩
    enabled: true
    mime-types: application/javascript,text/css,application/json,application/xml,text/html,text/xml,text/plain
    min-response-size: 2048
  tomcat:
    max-threads: 300
    accept-count: 300
    min-spare-threads: 50
    max-connections: 15000
    connection-timeout: 60000

FilterConfig 配置

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterBean = new FilterRegistrationBean();
        filterBean.setFilter(new AddContentLengthFilter());
        filterBean.setUrlPatterns(Arrays.asList("*"));
        return filterBean;
    }

    class AddContentLengthFilter extends OncePerRequestFilter {

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

            ContentCachingResponseWrapper cacheResponseWrapper;
            if (!(response instanceof ContentCachingResponseWrapper)) {
                cacheResponseWrapper = new ContentCachingResponseWrapper(response);
            } else {
                cacheResponseWrapper = (ContentCachingResponseWrapper) response;
            }

            filterChain.doFilter(request, cacheResponseWrapper);

            cacheResponseWrapper.copyBodyToResponse();
        }
    }
}

这里添加了一个Filter,在这个Filter中,使用了ContentCachingResponseWrapper包装response。ContentCachingResponseWrapper会缓存所有写给OutputStream的数据,并且因为缓存了内容,所以可以获取Content-Length并帮忙设置。

测试

使用Postman 模拟请求,查询系统配置接口,未压缩前请求体 17K左右,请求如下:

增加压缩配置后,请求体只有 3.5K左右。

最近发表
标签列表