JAVA:Spring Boot 集成 Deflate 实现无损压缩

admin
1
2026-03-26

1、简述

在 Web 开发中,数据压缩是提升传输效率的重要手段。除了常见的 Gzip 压缩,Deflate 也是一种高效的压缩算法,广泛应用于 HTTP 压缩、数据存储和传输。本文将介绍如何在 Spring Boot 中集成 Deflate 压缩,并通过示例演示如何压缩和解压缩数据。

image-0kqd.png


2、什么是 Deflate 压缩?

Deflate 是一种无损数据压缩算法,结合了 LZ77Huffman 编码,被广泛用于 HTTP 数据传输、ZIP 文件格式和 PNG 图片格式。

Gzip 的主要区别:

🔥 Deflate 仅是压缩算法,而 Gzip 包含文件头、校验和等额外信息。

🔥 Deflate 压缩比通常更高,但 Gzip 兼容性更好。


3、Spring Boot 处理 HTTP Deflate 压缩

3.1 启用 Deflate 压缩(配置方式)

Spring Boot 内置了对 GzipDeflate 的支持,我们可以在 application.yml 进行如下配置:

server:
  compression:
    enabled: true
    mime-types: application/json,application/xml,text/html,text/plain
    min-response-size: 1024
    # 指定支持的压缩类型,默认包含 Gzip,可以手动添加 Deflate
    types: gzip, deflate
  • enabled: true:开启压缩功能
  • mime-types:指定可压缩的内容类型
  • min-response-size:超过 1KB 的响应才会被压缩
  • types:支持 Gzip 和 Deflate

3.2 自定义 Deflate 压缩/解压缩工具类

Spring Boot 本身不会对请求/响应体进行手动压缩,我们可以创建一个工具类来压缩和解压缩数据。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class DeflateUtils {

    // 压缩数据
    public static byte[] compress(String data) throws IOException {
        if (data == null || data.isEmpty()) {
            return new byte[0];
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, new Deflater(Deflater.BEST_COMPRESSION))) {
            deflaterOutputStream.write(data.getBytes());
        }
        return byteArrayOutputStream.toByteArray();
    }

    // 解压缩数据
    public static String decompress(byte[] compressedData) throws IOException {
        if (compressedData == null || compressedData.length == 0) {
            return "";
        }

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedData);
        try (InflaterInputStream inflaterInputStream = new InflaterInputStream(byteArrayInputStream, new Inflater())) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inflaterInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            return outputStream.toString();
        }
    }
}

4、实践示例

创建 RESTful API 处理 Deflate 压缩数据

4.1 Controller 处理压缩/解压缩

import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/deflate")
public class DeflateController {

    // 发送压缩数据
    @PostMapping("/compress")
    public String compressData(@RequestBody String data) throws IOException {
        byte[] compressedData = DeflateUtils.compress(data);
        return Base64.getEncoder().encodeToString(compressedData);
    }

    // 解压缩数据
    @PostMapping("/decompress")
    public String decompressData(@RequestBody String compressedBase64) throws IOException {
        byte[] compressedData = Base64.getDecoder().decode(compressedBase64);
        return DeflateUtils.decompress(compressedData);
    }
}

4.2 测试请求

使用 PostmancURL 发送测试请求。

请求压缩
curl -X POST "http://localhost:8080/deflate/compress" \
     -H "Content-Type: text/plain" \
     -d "Hello, this is a Deflate compression test in Spring Boot!"
请求解压
curl -X POST "http://localhost:8080/deflate/decompress" \
     -H "Content-Type: text/plain" \
     -d "eJzLSM3JyVcIzy/KSVEEABxJBD4="   # 这里替换为压缩后的 Base64 字符串

4.3 Spring Boot 过滤器自动处理 Deflate 压缩

如果想要 自动处理所有 API 的数据压缩,可以使用 Spring Boot 过滤器:

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;

public class DeflateCompressionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Content-Encoding", "deflate");

        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(httpServletResponse.getOutputStream());
        chain.doFilter(request, new DeflateResponseWrapper(httpServletResponse, deflaterOutputStream));
    }
}

注册到 Spring Boot

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebConfig {
    @Bean
    public FilterRegistrationBean<DeflateCompressionFilter> deflateFilter() {
        FilterRegistrationBean<DeflateCompressionFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new DeflateCompressionFilter());
        registrationBean.addUrlPatterns("/api/*"); // 仅对 /api/ 开头的接口启用
        return registrationBean;
    }
}

5、总结

🔥 Spring Boot 可以通过 server.compression.enabled=true 直接支持 Deflate 压缩。

🔥 手动压缩/解压缩 需要使用 DeflaterOutputStreamInflaterInputStream

🔥 过滤器方式 可以自动对 API 响应进行 Deflate 压缩,适用于全局优化。

Deflate 是一个高效的压缩方案,在 Spring Boot 项目中可以灵活应用来提高传输和存储效率。

✅ 适用场景:

🔥 高并发环境:Deflate 压缩可降低网络传输压力。

🔥 大数据量传输:适用于 API 数据返回体积较大时。

🔥 存储优化:可用于数据库、日志或缓存数据压缩。

动物装饰