描述
proxy-cache 插件提供了缓存后端响应数据的能力,可以根据响应码和请求模式等属性来指定需要缓存的数据。
作用范围
该插件目前只支持用于路由级插件。
属性
名称 | 类型 | 必选项 | 默认值 | 有效值 | 描述 |
cache_key | array[string] | 可选 | ["\$host", "\$request_uri"] | 缓存 key,可以使用变量。例如:["\$host", "\$request_uri"] | |
cache_bypass | array[string] | 可选 | 当该属性的值不为空或者非 | ||
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 | 当设置为 | |
cache_control | boolean | 可选 | false | 当设置为 | |
no_cache | array[string] | 可选 | 当此参数的值不为空或非 | ||
cache_ttl | integer | 可选 | 300秒 | 当选项 |
如何启用
在配置窗口页以 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"}] |