• Spring-Cloud-Openfeign如何支持数据压缩?


    HTTP压缩的原理

    市面上主流的浏览器基本都支持gzip压缩,我们来看下服务端支持压缩的情况下,浏览器与服务端的通信过程:
    在这里插入图片描述

    第一步:浏览器发送Http request 给Web服务器, request头中有Accept-Encoding: gzip, deflate。(告诉服务器, 浏览器支持gzip压缩)
    第二步:Web服务器接到request后, 生成原始的Response, 其中有原始的Content-Type和Content-Length。
    第三步:Web服务器通过Gzip,来对Response进行编码, 编码后响应header中有Content-Type和Content-Length(压缩后的大小), 并且增加了Content-Encoding:gzip. 然后把Response发送给浏览器.
    第四步:浏览器接到Response后,根据Content-Encoding:gzip来对Response 进行解码。获取到原始response后, 然后显示出网页.

    让Springboot的服务端支持压缩

    springboot的服务端接口默认并没有开启压缩,需要手动开启:

    server:
      compression:
        enabled: true
        min-response-size: 1B
        mime-types:
          - "application/json"
          - "application/xml"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    测试一下:
    在这里插入图片描述

    可以看出来,服务端返回了Content-Encoding:gzip,说明响应是经过服务端压缩的。

    让feign调用支持压缩

    1)首先feign调用的server端需要支持压缩,前面已经有讲:

    server:
      compression:
        enabled: true
        min-response-size: 1B
        mime-types:
          - "application/json"
          - "application/xml"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2)feign发起请求的时候,需要在请求头中传递Accept-Encoding:gzip这个请求头,在收到Content-Encoding:gzip的响应头的时候还可以对结果做解压缩,需要做如下设置:

    feign:
      compression:
        request:
          enabled: true
          mime-types:
            - "application/xml"
            - "application/json"
          min-request-size: 1
        response:
          enabled: true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试一下:
    在这里插入图片描述

    完整的源码下载:https://github.com/xjs1919/enumdemo/tree/master/feign-compress-demo

  • 相关阅读:
    嵌入式Qt-做一个秒表
    iPhone NFC 设置教程(门禁卡/公交卡/校园卡等等)
    智慧运维:基于 BIM 技术的可视化管理系统
    Hbase Java API原理介绍
    react 中DatePicker 使用问题
    【数据库MySql】数据库基础——库和表的基础操作
    Ceres 数值导数 (NumericDerivatives)进阶
    【Linux】Shell使用sh和bash区别
    linux应用层操控硬件的方式
    Vue3基本使用
  • 原文地址:https://blog.csdn.net/goldenfish1919/article/details/132621561