SpringBoot系列教程Web篇之开启GZIP数据压缩

本篇可以归纳在性能调优篇,虽然内容非常简单,但效果可能出乎预料的好;

分享一个真实案例,我们的服务部署在海外,国内访问时访问服务时,响应有点夸张;某些返回数据比较大的接口,耗时在 600ms+上,然而我们的服务 rt 却是在 20ms 以下,绝大部分的开销都花在了网络传输上

针对这样的场景,除了买云服务商的网络通道之外,另外一个直观的想法就是减少数据包的大小,直接在 nginx 层配置 gzip 压缩是一个方案,本文主要介绍下,SpringBoot 如何开启 gzip 压缩

I. gizp 压缩配置

1. 配置

SpringBoot 默认是不开启 gzip 压缩的,需要我们手动开启,在配置文件中添加两行

server:
compression:
enabled: true
mime-types: application/json,application/xml,text/html,text/plain,text/css,application/x-javascript

注意下上面配置中的mime-types,在 spring2.0+的版本中,默认值如下,所以一般我们不需要特意添加这个配置

// org.springframework.boot.web.server.Compression#mimeTypes
/**
* Comma-separated list of MIME types that should be compressed.
*/
private String[] mimeTypes = new String[] { "text/html", "text/xml", "text/plain",
"text/css", "text/javascript", "application/javascript", "application/json",
"application/xml" };

2. 测试

写一个测试的 demo

@RestController
public class HelloRest {
@GetMapping("bigReq")
public String bigReqList() {
List<String> result = new ArrayList<>(2048);
for (int i = 0; i < 2048; i++) {
result.add(UUID.randomUUID().toString());
}
return JSON.toJSONString(result);
}
}

下面是开启压缩前后的数据报对比

3. 说明

虽然加上了上面的配置,开启了 gzip 压缩,但是需要注意并不是说所有的接口都会使用 gzip 压缩,默认情况下,仅会压缩 2048 字节以上的内容

如果我们需要修改这个值,通过修改配置即可

server:
compression:
min-response-size: 1024

II. 其他

0. 项目

web 系列博文
项目源码
  • 工程:https://github.com/liuyueyi/spring-boot-demo[1]

  • 项目:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/210-web-filter[2]

1. 一灰灰 Blog

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现 bug 或者有更好的建议,欢迎批评指正,不吝感激

下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

  • 一灰灰 Blog 个人博客 https://blog.hhui.top[3]

  • 一灰灰 Blog-Spring 专题博客 http://spring.hhui.top[4]

一灰灰blog

参考资料

[1]

https://github.com/liuyueyi/spring-boot-demo: https://github.com/liuyueyi/spring-boot-demo

[2]

https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/210-web-filter: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/210-web-filter

[3]

https://blog.hhui.top: https://blog.hhui.top

[4]

http://spring.hhui.top: http://spring.hhui.top

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一灰灰blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值