配置代理缓存
proxy-cache插件可以在网关中缓存上游响应,显著缩短频繁请求资源的响应时间,并降低后端服务负载。
前置条件
- API7 企业版实例正在运行。
- 已创建网关组且网关实例正在运行。
- 一个 Dashboard Token。
- 如需使用自定义缓存区域,请在网关的 Nginx 配置中进行配置,例如
disk_cache_one或memory_cache。
配置基于磁盘的代理缓存
插件默认使用基于磁盘的缓存,网关重启后仍会保留。
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/services/proxy-cache-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "proxy-cache-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [{"host": "httpbin.org", "port": 80, "weight": 100}]
}
}'
curl -k "https://localhost:7443/apisix/admin/routes/proxy-cache-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "proxy-cache-route",
"methods": ["GET"],
"paths": ["/anything/cache"],
"service_id": "proxy-cache-service",
"plugins": {"proxy-cache": {"cache_strategy": "disk", "hide_cache_headers": false}}
}'
adc.yaml
services:
- name: proxy-cache-service
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
routes:
- name: proxy-cache-route
uris:
- /anything/cache
methods:
- GET
plugins:
proxy-cache:
cache_strategy: disk
hide_cache_headers: false
adc sync -f adc.yaml
配置基于内存的代理缓存
基于内存的缓存访问速度比磁盘缓存快,但重启后不会保留。
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/services/memory-proxy-cache-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "memory-proxy-cache-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [{"host": "httpbin.org", "port": 80, "weight": 100}]
}
}'
curl -k "https://localhost:7443/apisix/admin/routes/memory-proxy-cache-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "memory-proxy-cache-route",
"methods": ["GET"],
"paths": ["/anything/cache-memory"],
"service_id": "memory-proxy-cache-service",
"plugins": {
"proxy-cache": {
"cache_strategy": "memory",
"cache_zone": "memory_cache",
"hide_cache_headers": false,
"cache_ttl": 60
}
}
}'
adc.yaml
services:
- name: memory-proxy-cache-service
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
routes:
- name: memory-proxy-cache-route
uris:
- /anything/cache-memory
methods:
- GET
plugins:
proxy-cache:
cache_strategy: memory
cache_zone: memory_cache
hide_cache_headers: false
cache_ttl: 60
adc sync -f adc.yaml
验证配置
向路由发送多个请求:
curl -i "http://127.0.0.1:9080/anything/cache"
curl -i "http://127.0.0.1:9080/anything/cache"
检查响应头。如果 hide_cache_headers 为 false,将看到 Apisix-Cache-Status:
MISS:缓存中没有响应,已从上游获取。HIT:响应来自缓存。EXPIRED:缓存响应已存在但已过期,已获取新响应。
对于内存缓存示例,请请求两次 http://127.0.0.1:9080/anything/cache-memory。第一次响应应包含 Apisix-Cache-Status: MISS,第二次应包含 Apisix-Cache-Status: HIT。
如果应用配置后路由立即返回 404,请等待几秒,让最新配置下发到网关后重试。