本篇可以归纳在性能调优篇,虽然内容非常简单,但效果可能出乎预料的好;
分享一个真实案例,我们的服务部署在海外,国内访问时访问服务时,响应有点夸张;某些返回数据比较大的接口,耗时在 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 系列博文
191012-SpringBoot 系列教程 web 篇之自定义异常处理 HandlerExceptionResolver
190213-SpringBoot 文件上传异常之提示 The temporary upload location xxx is not valid
项目源码
工程: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]
参考资料
[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