proxy-cache
proxy-cache 插件根据缓存键缓存响应。该插件支持磁盘和内存两种缓存方式,可缓存 GET、POST 和 HEAD 请求。
可以根据请求 HTTP 方法、响应状态码、请求头值等条件有选择地缓存响应。
默认情况下,已认证消费者使用相互隔离的有效缓存键。该隔离行为自 API7 企业版 3.9.13 和 APISIX 3.17.0 起提供。除非启用 cache_set_cookie,否则内存缓存策略不会缓存包含 Set-Cookie 的响应;对于上游标记为 private、no-store 或 no-cache 的响应则一律不缓存。
示例
以下示例演示了如何在不同场景下配置 proxy-cache。
在磁盘上缓存数据
与内存缓存相比,磁盘缓存策略具有系统重启时数据持久化和存储容量更大的优点。它适用于优先考虑持久性并且可以容忍稍大的缓存访问延迟的应用程序。
以下示例演示了如何在路由上使用 proxy-cache 插件将数据缓存在磁盘上。
使用磁盘缓存策略时,缓存 TTL 由 Expires 或 Cache-Control 响应头决定。如果两个响应头均不存在,或者 APISIX 因上游不可用而返回 502 Bad Gateway 或 504 Gateway Timeout,缓存 TTL 将使用配置文件中配置的默认值。
创建一个使用 proxy-cache 插件的路由以在磁盘上缓存数据:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "proxy-cache-route",
"uri": "/anything",
"plugins": {
"proxy-cache": {
"cache_strategy": "disk"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org": 1
}
}
}'
services:
- name: proxy-cache-service
routes:
- name: proxy-cache-route
uris:
- /anything
plugins:
proxy-cache:
cache_strategy: disk
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
将配置同步到网关:
adc sync -f adc.yaml
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin-external-domain
spec:
type: ExternalName
externalName: httpbin.org
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: proxy-cache-plugin-config
spec:
plugins:
- name: proxy-cache
config:
cache_strategy: disk
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: proxy-cache-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /anything
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: proxy-cache-plugin-config
backendRefs:
- name: httpbin-external-domain
port: 80
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: httpbin-external-domain
spec:
ingressClassName: apisix
externalNodes:
- type: Domain
name: httpbin.org
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: proxy-cache-route
spec:
ingressClassName: apisix
http:
- name: proxy-cache-route
match:
paths:
- /anything
upstreams:
- name: httpbin-external-domain
plugins:
- name: proxy-cache
enable: true
config:
cache_strategy: disk
将配置应用到集群:
kubectl apply -f proxy-cache-ic.yaml
向路由发送请求:
curl -i "http://127.0.0.1:9080/anything"
你应该会看到 HTTP/1.1 200 OK 响应,并带有以下响应头,表明插件已成功启用:
Apisix-Cache-Status: MISS
由于第一个响应之前没有可用缓存,因此显示 Apisix-Cache-Status: MISS。
在缓存 TTL 窗口内再次发送相同的请求。你应该会看到 HTTP/1.1 200 OK 响应,并带有以下响应头,表明缓存命中:
Apisix-Cache-Status: HIT
等待缓存超过 TTL 后过期,然后再次发送相同的请求。你应该会看到 HTTP/1.1 200 OK 响应,并带有以下响应头,表明缓存已过期:
Apisix-Cache-Status: EXPIRED