首页 > 数据库 > 数据库开发技术 > Spring Boot启用GZIP压缩
经常我们都会与服务端进行大数据量的文本传输,例如 JSON 就是常见的一种格式。通过 REST API 接口进行 GET 和 POST 请求,可能会有大量的文本格式数据提交、返回。然后对于文本,它有很高的压缩率,如果在 GET/POST 请求时候对文本进行压缩会节省大量的网络带宽,减少网络时延。 HTTP 协议在相应部分支持 Content-Encoding: gzip ,浏览器请求时带上 Accept-Encoding: gzip 即可,服务端对返回的 response body 进行压缩,并在 response 头带上 Content-Encoding: gzip,浏览器会自动解析。 然而 HTTP 没有压缩 request body 的设计,因为在客户端发起请求时并不知道服务器是否支持压缩。因此没法通过 HTTP 协议来解决,只能在服务端做一些过滤器进行判断,人为约束。压缩和解压在提升网络带宽的同时,会带来 CPU 资源的损耗。
对返回的json启用gzip压缩
<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"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>gzip</artifactId><properties><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-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><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-data-redis</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.9.0</version></dependency></dependencies></project>
请求和响应都是同一个user对象,方便后面测试对比它们的大小
package com.et.gzip.controller;import com.et.gzip.model.User;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;@RestController@Slf4jpublic class HelloWorldController {@PostMapping("/hello")public User showHelloWorld(@RequestBody User user){log.info("user:"+ user);return user;}}
server:port: 8088compression:enabled: true: application/json,application/xml,text/html,text/plain,text/css,application/x-javascript
以上只是一些关键代码,所有代码请参见下面代码仓库
https://github.com/Harries/springboot-demo(gzip)
启动 Spring Boot工程
用postman请求http://127.0.0.1:8088/hello
可以看到 request body 285B,respnse body 64B ,将近5倍的差距。
http://www.liuhaihua.cn/archives/711208.html

如果觉得文章对您有帮助的话,请帮忙关注/留言/转发!另外最近写的一个《Spring Boot快速入门》专栏,大家可以去看看,对新手友好,极简入门。没有冗余的理论知识,直接上干货代码。方便在实际项目中快速应用!
原文作者:HBLOG;如有侵权,请联系管理员删除。