191120-SpringBoot系列教程Web篇之开启GZIP数据压缩
source link: http://spring.hhui.top/spring-blog/2019/11/20/191120-SpringBoot系列教程Web篇之开启GZIP数据压缩/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
本篇可以归纳在性能调优篇,虽然内容非常简单,但效果可能出乎预料的好;
分享一个真实案例,我们的服务部署在海外,国内访问时访问服务时,响应有点夸张;某些返回数据比较大的接口,耗时在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系列博文
- 191018-SpringBoot系列教程web篇之过滤器Filter使用指南扩展篇
- 191016-SpringBoot系列教程web篇之过滤器Filter使用指南
- 191012-SpringBoot系列教程web篇之自定义异常处理HandlerExceptionResolver
- 191010-SpringBoot系列教程web篇之全局异常处理
- 190930-SpringBoot系列教程web篇之404、500异常页面配置
- 190929-SpringBoot系列教程web篇之重定向
- 190913-SpringBoot系列教程web篇之返回文本、网页、图片的操作姿势
- 190905-SpringBoot系列教程web篇之中文乱码问题解决
- 190831-SpringBoot系列教程web篇之如何自定义参数解析器
- 190828-SpringBoot系列教程web篇之Post请求参数解析姿势汇总
- 190824-SpringBoot系列教程web篇之Get请求参数解析姿势汇总
- 190822-SpringBoot系列教程web篇之Beetl环境搭建
- 190820-SpringBoot系列教程web篇之Thymeleaf环境搭建
- 190816-SpringBoot系列教程web篇之Freemaker环境搭建
- 190421-SpringBoot高级篇WEB之websocket的使用说明
- 190327-Spring-RestTemplate之urlencode参数解析异常全程分析
- 190317-Spring MVC之基于java config无xml配置的web应用构建
- 190316-Spring MVC之基于xml配置的web应用构建
- 190213-SpringBoot文件上传异常之提示The temporary upload location xxx is not valid
项目源码
- 工程: https://github.com/liuyueyi/spring-boot-demo
- 项目: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/210-web-filter
1. 一灰灰Blog
尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激
下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
- 一灰灰Blog个人博客 https://blog.hhui.top
- 一灰灰Blog-Spring专题博客 http://spring.hhui.top
打赏 如果觉得我的文章对您有帮助,请随意打赏。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK