微服务引擎MSE

结果缓存proxy-cache插件

2025-05-27 07:55:03

描述

proxy-cache 插件提供了缓存后端响应数据的能力,可以根据响应码和请求模式等属性来指定需要缓存的数据。

作用范围

该插件目前只支持用于路由级插件。

属性

名称

类型

必选项

默认值

有效值

描述

cache_key

array[string]

可选

["\$host", "\$request_uri"]


缓存 key,可以使用变量。例如:["\$host", "\$request_uri"]

cache_bypass

array[string]

可选



当该属性的值不为空或者非0时则会跳过缓存检查,即不在缓存中查找数据,可以使用变量,例如:["$arg_bypass"]

cache_method

array[string]

可选

["GET", "HEAD"]

["GET", "POST", "HEAD"]

根据请求method决定是否需要缓存。

cache_http_status

array[integer]

可选

[200, 301, 404]

[200, 599]

根据HTTP响应码决定是否需要缓存。

hide_cache_headers

boolean

可选

false


当设置为true时将ExpiresCache-Control响应头返回给客户端。

cache_control

boolean

可选

false


当设置为true时遵守HTTP协议规范中的Cache-Control的行为。

no_cache

array[string]

可选



当此参数的值不为空或非0时将不会缓存数据,可以使用变量

cache_ttl

integer

可选

300


当选项cache_control未开启或开启以后服务端没有返回缓存控制头时,提供的默认缓存时间。

 

如何启用

在配置窗口页以 YAML 格式填写

配置示例

下面是一个示例,开启 proxy-cache 插件,并配置了一些属性。表示对于路径为“/hello”的路由,在60秒内,对于返回结果为200的GET请求将返回缓存结果,其中缓存的key为请求uri+"-cache-id"的拼接字符串。

curl http://127.0.0.1:9180/apisix/admin/routes/1   \

-H 'X-API-KEY:   edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '

{

    "plugins": {

        "proxy-cache": {

            "cache_key":  ["$uri", "-cache-id"],

            "cache_bypass":   ["$arg_bypass"],

            "cache_method":   ["GET"],

            "cache_http_status":   [200],

            "hide_cache_headers":   true,

            "cache_control": false,

                "cache_ttl": 60

        }

    },

    "upstream": {

        "nodes": {

            "127.0.0.1:1999": 1

        },

        "type":   "roundrobin"

    },

    "uri": "/hello"

}'

启用/停用

在路由上绑定/解绑插件。

验证插件

在路由上绑定结果缓存插件后,第一次请求Apisix-Cache-Status状态为MISS

$curl -i   127.0.0.1:27151/api/1/reviews

HTTP/1.1 200

Content-Type:   application/json

Transfer-Encoding:   chunked

Connection: keep-alive

Apisix-Cache-Status:   MISS

Date: Mon, 18 Mar 2024   12:02:07 GMT

Server: APISIX/2.13.3

 

[{"id":1,"productId":1,"reviewer":"Reviewer1","text":"This   is the 1st reviewer"}]

再次请求,命中缓存,Apisix-Cache-Status状态为HIT

$ curl -i   127.0.0.1:27151/api/1/reviews

HTTP/1.1 200 OK

Content-Type:   application/json

Transfer-Encoding:   chunked

Connection: keep-alive

Date: Mon, 18 Mar 2024   12:02:07 GMT

Server: APISIX/2.13.3

Age: 3

Apisix-Cache-Status:   HIT

 

[{"id":1,"productId":1,"reviewer":"Reviewer1","text":"This   is the 1st reviewer"}]


eQR6oOLdEA92