1.为什么是需要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 资源的损耗。
2.代码工程
实验目的
对返回的json启用gzip压缩
pom.xml
<?xml version="1.0" encoding="utf-8"?> <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>
controller
请求和响应都是同一个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 @slf4j public class helloworldcontroller { @postmapping("/hello") public user showhelloworld(@requestbody user user){ log.info("user:"+ user); return user; } }
application.yaml
server: port: 8088 compression: enabled: true mime-types: application/json,application/xml,text/html,text/plain,text/css,application/x-javascript
以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库
3.测试
用postman请求http://127.0.0.1:8088/hello
可以看到 request body 285b,respnse body 64b ,将近5倍的差距。
以上就是springboot启用gzip压缩的代码工程的详细内容,更多关于springboot启用gzip压缩的资料请关注代码网其它相关文章!
发表评论