GraphQL Limit Count
graphql-limit-count 插件使用固定窗口或滑动窗口,限制 GraphQL 查询和变更的累计成本。默认以查询深度作为成本,也可使用 complexity 和 node_quantifier 策略,根据文档请求的处理工作量计算成本。
在 GraphQL 中,深度是指查询或变更的嵌套层数。以下是深度为 3 的查询示例:
{
a {
b {
c
}
}
}
采用默认的深度策略时,插件在每个时间间隔内按深度消耗配额。例如,30 秒内的配额为 4 时,深度为 3 的请求会被允许,剩余配额为 1;同一时间间隔内深度为 2 的请求则会被拒绝。
插件接受 POST 请求,请求体可以是包含 query 字段的 JSON,或包含 GraphQL 文档的 application/graphql。片段会参与查询深度的计算。不支持的方法返回 405 Method Not Allowed; 无法读取、格式错误或无效的 GraphQL 请求返回 400 Bad Request。
高级成本策略、Schema 内省及服务级成本装饰的说明,请参阅 GraphQL 查询成本参考。
本地限速与基于 Redis 的限速
graphql-limit-count 插件支持本地限速和基于 Redis 的限速:
- 本地限速:每个网关实例独立实施限速。各实例维护自己的计数器,因此当流量分散到多个实例时,实际限额约为“限额 × 实例数”。未设置
policy或将其设置为local时,这是默认模式。 - 基于 Redis 的限速:通过 Redis 服务器、Redis Cluster 或 Redis Sentinel 部署,在各个网关实例之间共享限额。所有实例共用同一配额。
示例
这些示例使用公开的 Countries GraphQL API 作为上游,无需账号或访问 Token。
使用 Ingress Controller 标签页前,请先完成设置 Ingress Controller 和网关。Gateway API 示例使用 APISIX 部署中位于 aic 命名空间、名为 apisix 的 Gateway;使用其他部署(包括 API7 网关)时,请将其替换为实际安装的 Gateway 名称。
基于远程地址进行限速
以下示例展示如何为每个客户端地址分配独立的查询成本配额。
创建路由,允许每个远程地址在每个 30 秒窗口内使用的查询深度总和为 2:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes/graphql-limit-count-route" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"uri": "/graphql-limit",
"plugins": {
"proxy-rewrite": {
"uri": "/graphql"
},
"graphql-limit-count": {
"count": 2,
"time_window": 30,
"rejected_code": 429,
"key_type": "var",
"key": "remote_addr",
"policy": "local"
}
},
"upstream": {
"type": "roundrobin",
"pass_host": "node",
"scheme": "https",
"nodes": {
"countries.trevorblades.com:443": 1
}
}
}'
services:
- name: graphql-service
labels:
docs-example: graphql-limit-remote
routes:
- uris:
- /graphql-limit
name: graphql-limit-count-route
plugins:
proxy-rewrite:
uri: /graphql
graphql-limit-count:
count: 2
time_window: 30
rejected_code: 429
key_type: var
key: remote_addr
policy: local
upstream:
type: roundrobin
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
预览本示例所管理资源的变更,确认差异中没有意外更新或删除:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-remote
同步已审查的服务配置:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-remote
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
type: ExternalName
externalName: countries.trevorblades.com
ports:
- name: https
port: 443
targetPort: 443
---
apiVersion: apisix.apache.org/v1alpha1
kind: BackendTrafficPolicy
metadata:
namespace: aic
name: countries-graphql-https
spec:
targetRefs:
- name: countries-graphql-external-domain
kind: Service
group: ""
sectionName: https
passHost: node
scheme: https
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: graphql-limit-count-plugin-config
spec:
plugins:
- name: proxy-rewrite
config:
uri: /graphql
- name: graphql-limit-count
config:
count: 2
time_window: 30
rejected_code: 429
key_type: var
key: remote_addr
policy: local
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: graphql-limit-count-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /graphql-limit
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: graphql-limit-count-plugin-config
backendRefs:
- name: countries-graphql-external-domain
port: 443
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
ingressClassName: apisix
scheme: https
passHost: node
externalNodes:
- type: Domain
name: countries.trevorblades.com
port: 443
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: graphql-limit-count-route
spec:
ingressClassName: apisix
http:
- name: graphql-limit-count-route
match:
paths:
- /graphql-limit
upstreams:
- name: countries-graphql-external-domain
plugins:
- name: proxy-rewrite
enable: true
config:
uri: /graphql
- name: graphql-limit-count
enable: true
config:
count: 2
time_window: 30
rejected_code: 429
key_type: var
key: remote_addr
policy: local
将配置应用到集群:
kubectl apply -f graphql-limit-count-ic.yaml
验证 GraphQL 查询
发送包含深度为 2 的 GraphQL 查询的请求进行验证:
curl -i "http://127.0.0.1:9080/graphql-limit" -X POST \
-H "Content-Type: application/json" \
-d '{"query": "query { country(code: \"US\") { name } }"}'
首次请求应返回 200 OK,响应头包含 X-RateLimit-Remaining: 0,响应体中包含美国的数据。
该请求会耗尽可用配额。在同一 30 秒窗口内重复请求,第二次请求应返回 429 Too Many Requests。
验证 GraphQL 变更
Countries API 是只读的,但插件会在请求到达上游前评估变更。发送语法有效、深度为 3 的变更:
curl -i "http://127.0.0.1:9080/graphql-limit" -X POST \
-H "Content-Type: application/json" \
-d '{"query":"mutation { updateCountry { country { name } } }"}'
由于深度超过配置的配额,请求应返回 429 Too Many Requests。请求会在只读上游验证操作前被拒绝。
按查询复杂度限速
complexity 策略和 max_cost 在 API7 企业版 3.10.6 和 APISIX 3.19.0 中引入。
以下示例根据查询解析的节点而非深度计算原始分数,并拒绝计入配额的成本超过固定预算的查询。
创建启用 graphql-limit-count 插件并使用 complexity 策略的路由。每个远程地址在 30 秒窗口内的配额为 100,成本超过 6 的单个查询会被拒绝:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes/graphql-cost-route" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"uri": "/graphql-complexity-limit",
"plugins": {
"proxy-rewrite": {
"uri": "/graphql"
},
"graphql-limit-count": {
"count": 100,
"time_window": 30,
"rejected_code": 429,
"key_type": "var",
"key": "remote_addr",
"policy": "local",
"show_limit_quota_header": true,
"cost_strategy": "complexity",
"max_cost": 6
}
},
"upstream": {
"type": "roundrobin",
"pass_host": "node",
"scheme": "https",
"nodes": {
"countries.trevorblades.com:443": 1
}
}
}'
services:
- name: graphql-service
labels:
docs-example: graphql-limit-complexity
routes:
- uris:
- /graphql-complexity-limit
name: graphql-cost-route
plugins:
proxy-rewrite:
uri: /graphql
graphql-limit-count:
count: 100
time_window: 30
rejected_code: 429
key_type: var
key: remote_addr
policy: local
show_limit_quota_header: true
cost_strategy: complexity
max_cost: 6
upstream:
type: roundrobin
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
预览本示例所管理资源的变更,确认差异中没有意外更新或删除:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-complexity
同步已审查的服务配置:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-complexity
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
type: ExternalName
externalName: countries.trevorblades.com
ports:
- name: https
port: 443
targetPort: 443
---
apiVersion: apisix.apache.org/v1alpha1
kind: BackendTrafficPolicy
metadata:
namespace: aic
name: countries-graphql-https
spec:
targetRefs:
- name: countries-graphql-external-domain
kind: Service
group: ""
sectionName: https
passHost: node
scheme: https
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: graphql-cost-plugin-config
spec:
plugins:
- name: proxy-rewrite
config:
uri: /graphql
- name: graphql-limit-count
config:
count: 100
time_window: 30
rejected_code: 429
key_type: var
key: remote_addr
policy: local
show_limit_quota_header: true
cost_strategy: complexity
max_cost: 6
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: graphql-cost-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /graphql-complexity-limit
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: graphql-cost-plugin-config
backendRefs:
- name: countries-graphql-external-domain
port: 443
将配置应用到集群:
kubectl apply -f graphql-cost-ic.yaml
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
type: ExternalName
externalName: countries.trevorblades.com
ports:
- name: https
port: 443
targetPort: 443
---
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
ingressClassName: apisix
passHost: node
scheme: https
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: graphql-cost-route
spec:
ingressClassName: apisix
http:
- name: graphql-cost-route
match:
paths:
- /graphql-complexity-limit
backends:
- serviceName: countries-graphql-external-domain
servicePort: 443
plugins:
- name: proxy-rewrite
enable: true
config:
uri: /graphql
- name: graphql-limit-count
enable: true
config:
count: 100
time_window: 30
rejected_code: 429
key_type: var
key: remote_addr
policy: local
show_limit_quota_header: true
cost_strategy: complexity
max_cost: 6
将配置应用到集群:
kubectl apply -f graphql-cost-ic.yaml
向网关实例发送一个小型查询:
curl -i "http://127.0.0.1:9080/graphql-complexity-limit" -X POST \
-H "Content-Type: application/json" \
-d '{"query": "query { country(code: \"US\") { name } }"}'
响应应返回 200 OK,并报告计入配额的成本:
X-Graphql-Query-Cost: 4
发送计入配额的成本超过预算的查询:
curl -i "http://127.0.0.1:9080/graphql-complexity-limit" -X POST \
-H "Content-Type: application/json" \
-d '{"query": "query { country(code: \"US\") { code name native phone capital currency emoji continent { name } languages { name } } }"}'
应看到 HTTP/1.1 403 Forbidden 响应,查询不会到达上游:
{"message":"Invalid graphql request: query cost 14 exceeds max_cost 6"}
基于远程地址和消费者名称进行限速
以下示例展示如何组合客户端地址和消费者名称,使来自同一地址的每个已认证消费者获得独立配额。每个 Key 组合在 30 秒窗口内可使用的查询深度总和为 2。
- Admin API
- ADC
- Ingress Controller
创建消费者 john:
curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "john"
}'
为消费者创建 key-auth 凭据:
curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "cred-john-key-auth",
"plugins": {
"key-auth": {
"key": "john-key"
}
}
}'
创建第二个消费者 jane:
curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "jane"
}'
为消费者创建 key-auth 凭据:
curl "http://127.0.0.1:9180/apisix/admin/consumers/jane/credentials" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "cred-jane-key-auth",
"plugins": {
"key-auth": {
"key": "jane-key"
}
}
}'
创建启用 key-auth 和 graphql-limit-count 插件的路由:
curl "http://127.0.0.1:9180/apisix/admin/routes/graphql-limit-count-route" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"uri": "/graphql-consumer-limit",
"plugins": {
"key-auth": {},
"proxy-rewrite": {
"uri": "/graphql"
},
"graphql-limit-count": {
"count": 2,
"time_window": 30,
"rejected_code": 429,
"policy": "local",
"key_type": "var_combination",
"key": "$remote_addr $consumer_name"
}
},
"upstream": {
"type": "roundrobin",
"pass_host": "node",
"scheme": "https",
"nodes": {
"countries.trevorblades.com:443": 1
}
}
}'
创建两个消费者及一条按消费者限速的路由:
consumers:
- username: john
labels:
docs-example: graphql-limit-consumer
credentials:
- name: key-auth
type: key-auth
config:
key: john-key
- username: jane
labels:
docs-example: graphql-limit-consumer
credentials:
- name: key-auth
type: key-auth
config:
key: jane-key
services:
- name: graphql-limit-service
labels:
docs-example: graphql-limit-consumer
routes:
- name: graphql-limit-count-route
uris:
- /graphql-consumer-limit
plugins:
proxy-rewrite:
uri: /graphql
key-auth: {}
graphql-limit-count:
count: 2
time_window: 30
rejected_code: 429
policy: local
key_type: var_combination
key: "$remote_addr $consumer_name"
upstream:
type: roundrobin
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
预览本示例所管理资源的变更,确认差异中没有意外更新或删除:
adc diff -f adc.yaml \
--include-resource-type service \
--include-resource-type consumer \
--label-selector docs-example=graphql-limit-consumer
同步已审查的服务配置:
adc sync -f adc.yaml \
--include-resource-type service \
--include-resource-type consumer \
--label-selector docs-example=graphql-limit-consumer
创建两个消费者及一条按消费者限速的路由:
- Gateway API
- APISIX CRD
apiVersion: apisix.apache.org/v1alpha1
kind: Consumer
metadata:
namespace: aic
name: john
spec:
gatewayRef:
name: apisix
credentials:
- type: key-auth
name: primary-key
config:
key: john-key
---
apiVersion: apisix.apache.org/v1alpha1
kind: Consumer
metadata:
namespace: aic
name: jane
spec:
gatewayRef:
name: apisix
credentials:
- type: key-auth
name: primary-key
config:
key: jane-key
---
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
type: ExternalName
externalName: countries.trevorblades.com
ports:
- name: https
port: 443
targetPort: 443
---
apiVersion: apisix.apache.org/v1alpha1
kind: BackendTrafficPolicy
metadata:
namespace: aic
name: countries-graphql-https
spec:
targetRefs:
- name: countries-graphql-external-domain
kind: Service
group: ""
sectionName: https
passHost: node
scheme: https
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: graphql-limit-count-plugin-config
spec:
plugins:
- name: proxy-rewrite
config:
uri: /graphql
- name: key-auth
config:
_meta:
disable: false
- name: graphql-limit-count
config:
count: 2
time_window: 30
rejected_code: 429
policy: local
key_type: var_combination
key: "$remote_addr $consumer_name"
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: graphql-limit-count-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /graphql-consumer-limit
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: graphql-limit-count-plugin-config
backendRefs:
- name: countries-graphql-external-domain
port: 443
apiVersion: apisix.apache.org/v2
kind: ApisixConsumer
metadata:
namespace: aic
name: john
spec:
ingressClassName: apisix
authParameter:
keyAuth:
value:
key: john-key
---
apiVersion: apisix.apache.org/v2
kind: ApisixConsumer
metadata:
namespace: aic
name: jane
spec:
ingressClassName: apisix
authParameter:
keyAuth:
value:
key: jane-key
---
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
ingressClassName: apisix
scheme: https
passHost: node
externalNodes:
- type: Domain
name: countries.trevorblades.com
port: 443
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: graphql-limit-count-route
spec:
ingressClassName: apisix
http:
- name: graphql-limit-count-route
match:
paths:
- /graphql-consumer-limit
upstreams:
- name: countries-graphql-external-domain
plugins:
- name: proxy-rewrite
enable: true
config:
uri: /graphql
- name: key-auth
enable: true
- name: graphql-limit-count
enable: true
config:
count: 2
time_window: 30
rejected_code: 429
policy: local
key_type: var_combination
key: "$remote_addr $consumer_name"
将配置应用到集群:
kubectl apply -f graphql-limit-count-ic.yaml
❶ key-auth 在路由上启用密钥认证。
❷ key_type: var_combination 将 key 解释为变量组合。
❸ key 组合客户端地址和消费者名称,使解析出的每对组合都有独立配额。
以消费者 jane 的身份,发送包含深度为 2 的 GraphQL 查询的请求:
curl -i "http://127.0.0.1:9080/graphql-consumer-limit" -X POST \
-H "Content-Type: application/json" \
-H 'apikey: jane-key' \
-d '{"query": "query { country(code: \"US\") { name } }"}'
请求应返回 200 OK,响应头包含 X-RateLimit-Remaining: 0,响应体中包含美国的数据。
该请求会耗尽 Jane 的可用配额。在同一 30 秒窗口内以 Jane 的身份重复请求,应返回 429 Too Many Requests。
在同一 30 秒时间间隔内,以消费者 john 的身份发送相同请求:
curl -i "http://127.0.0.1:9080/graphql-consumer-limit" -X POST \
-H "Content-Type: application/json" \
-H 'apikey: john-key' \
-d '{"query": "query { country(code: \"US\") { name } }"}'
John 的首次请求也应返回 200 OK,并带有 X-RateLimit-Remaining: 0,确认其使用的计数器与 Jane 的请求不同。
在同一窗口内以 John 的身份重复请求,第二次请求应返回 429 Too Many Requests。
这些结果确认,插件为每个解析出的地址与消费者组合 Key 维护独立计数器。
在路由间共享配额
以下示例展示如何将两个路由分配到同一插件 group,使它们消耗同一份查询成本配额。
共享 group 的路由必须使用相同的 graphql-limit-count 配置。为保持配置一致,请将插件和上游配置到服务,再将路由关联到该服务。
- Admin API
- ADC
- Ingress Controller
创建服务:
curl "http://127.0.0.1:9180/apisix/admin/services/graphql-limit-count-service" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"plugins": {
"graphql-limit-count": {
"count": 2,
"time_window": 30,
"rejected_code": 429,
"policy": "local",
"group": "graphql-srv1"
}
},
"upstream": {
"type": "roundrobin",
"pass_host": "node",
"scheme": "https",
"nodes": {
"countries.trevorblades.com:443": 1
}
}
}'
创建第一条路由,并将其关联到该服务:
curl "http://127.0.0.1:9180/apisix/admin/routes/graphql-limit-count-route-1" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"service_id": "graphql-limit-count-service",
"uri": "/graphql1",
"plugins": {
"proxy-rewrite": {
"uri": "/graphql"
}
}
}'
创建第二条路由,并将其关联到同一服务:
curl "http://127.0.0.1:9180/apisix/admin/routes/graphql-limit-count-route-2" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"service_id": "graphql-limit-count-service",
"uri": "/graphql2",
"plugins": {
"proxy-rewrite": {
"uri": "/graphql"
}
}
}'
创建服务及两条共享同一限速配额的路由:
services:
- name: graphql-limit-count-service
labels:
docs-example: graphql-limit-group
plugins:
graphql-limit-count:
count: 2
time_window: 30
rejected_code: 429
policy: local
group: graphql-srv1
routes:
- name: graphql-limit-count-route-1
uris:
- /graphql1
plugins:
proxy-rewrite:
uri: /graphql
- name: graphql-limit-count-route-2
uris:
- /graphql2
plugins:
proxy-rewrite:
uri: /graphql
upstream:
type: roundrobin
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
预览本示例所管理资源的变更,确认差异中没有意外更新或删除:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-group
同步已审查的服务配置:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-group
- Gateway API
- APISIX CRD
创建两个引用同一 PluginConfig 的 HTTPRoute 资源,以共享配额:
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
type: ExternalName
externalName: countries.trevorblades.com
ports:
- name: https
port: 443
targetPort: 443
---
apiVersion: apisix.apache.org/v1alpha1
kind: BackendTrafficPolicy
metadata:
namespace: aic
name: countries-graphql-https
spec:
targetRefs:
- name: countries-graphql-external-domain
kind: Service
group: ""
sectionName: https
passHost: node
scheme: https
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: graphql-limit-count-plugin-config
spec:
plugins:
- name: graphql-limit-count
config:
count: 2
time_window: 30
rejected_code: 429
policy: local
group: graphql-srv1
- name: proxy-rewrite
config:
uri: /graphql
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: graphql-limit-count-route-1
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /graphql1
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: graphql-limit-count-plugin-config
backendRefs:
- name: countries-graphql-external-domain
port: 443
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: graphql-limit-count-route-2
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /graphql2
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: graphql-limit-count-plugin-config
backendRefs:
- name: countries-graphql-external-domain
port: 443
创建包含多个路径、共用同一插件配置的 ApisixRoute:
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
ingressClassName: apisix
scheme: https
passHost: node
externalNodes:
- type: Domain
name: countries.trevorblades.com
port: 443
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: graphql-limit-count-shared-route
spec:
ingressClassName: apisix
http:
- name: graphql-limit-count-shared
match:
paths:
- /graphql1
- /graphql2
upstreams:
- name: countries-graphql-external-domain
plugins:
- name: proxy-rewrite
enable: true
config:
uri: /graphql
- name: graphql-limit-count
enable: true
config:
count: 2
time_window: 30
rejected_code: 429
policy: local
group: graphql-srv1
将配置应用到集群:
kubectl apply -f graphql-limit-count-ic.yaml
两条路由都使用 proxy-rewrite,将各自的公开路径转发到上游 /graphql 端点。
向路由 /graphql1 发送包含深度为 2 的 GraphQL 查询的请求:
curl -i "http://127.0.0.1:9080/graphql1" -X POST \
-H "Content-Type: application/json" \
-d '{"query": "query { country(code: \"US\") { name } }"}'
第一条路由应返回 200 OK,并带有 X-RateLimit-Remaining: 0。
在同一 30 秒时间间隔内,向路由 /graphql2 发送相同的深度为 2 的查询:
curl -i "http://127.0.0.1:9080/graphql2" -X POST \
-H "Content-Type: application/json" \
-d '{"query": "query { country(code: \"US\") { name } }"}'
第二条路由应返回 429 Too Many Requests,确认两条路由消耗同一组配额。
使用 Redis 服务器在网关实例间共享配额
以下示例展示如何将查询成本计数器存储在同一个 Redis 服务器中,使加载相同路由资源的网关节点执行同一份共享配额。
启动 Redis
在网关使用的环境中启动 Redis。
- Docker
- Kubernetes
将 GATEWAY_CONTAINER 设置为正在运行的 APISIX 或 API7 网关容器名称。创建专用网络,并将网关连接到该网络:
export GATEWAY_CONTAINER=replace-with-gateway-container-name
docker network create gateway-graphql-limit-redis-net
docker network connect gateway-graphql-limit-redis-net "$GATEWAY_CONTAINER"
对每个额外用于验证共享计数器的网关容器,重复执行网络连接操作:
docker network connect gateway-graphql-limit-redis-net replace-with-additional-gateway-container
在共享网络上启动 Redis:
docker run -d \
--name redis-standalone \
--network gateway-graphql-limit-redis-net \
redis:8.10.2-alpine \
redis-server --requirepass redis-password
等待 Redis 就绪,然后验证需要认证的连接:
docker exec -e REDISCLI_AUTH=redis-password redis-standalone redis-cli ping
应收到 PONG。
在网关命名空间中创建 Redis Deployment 和 Service:
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: aic
name: redis-standalone
spec:
replicas: 1
selector:
matchLabels:
app: redis-standalone
template:
metadata:
labels:
app: redis-standalone
spec:
containers:
- name: redis
image: redis:8.10.2-alpine
args:
- redis-server
- --requirepass
- redis-password
ports:
- containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: redis-standalone
spec:
selector:
app: redis-standalone
ports:
- port: 6379
targetPort: 6379
应用清单,并等待 Redis 就绪:
kubectl apply -f redis-standalone.yaml
kubectl rollout status deployment/redis-standalone -n aic
这些演示环境使用教程密码和内部服务地址。生产环境中,请限制网络访问,将凭据作为 Secret 管理,启用持久化,并在支持的情况下配置 TLS。
创建路由
- Admin API
- ADC
- Ingress Controller
在网关集群或网关组中创建路由:
curl "http://127.0.0.1:9180/apisix/admin/routes/graphql-limit-count-route" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"uri": "/graphql-redis-limit",
"plugins": {
"proxy-rewrite": {
"uri": "/graphql"
},
"graphql-limit-count": {
"count": 2,
"time_window": 30,
"rejected_code": 429,
"key": "remote_addr",
"policy": "redis",
"redis_host": "redis-standalone",
"redis_port": 6379,
"redis_password": "redis-password",
"redis_database": 0
}
},
"upstream": {
"type": "roundrobin",
"pass_host": "node",
"scheme": "https",
"nodes": {
"countries.trevorblades.com:443": 1
}
}
}'
创建使用 Redis 限速的路由:
services:
- name: graphql-redis-limit-service
labels:
docs-example: graphql-limit-redis
routes:
- name: graphql-redis-limit-route
uris:
- /graphql-redis-limit
plugins:
proxy-rewrite:
uri: /graphql
graphql-limit-count:
count: 2
time_window: 30
rejected_code: 429
key: remote_addr
policy: redis
redis_host: redis-standalone
redis_port: 6379
redis_password: redis-password
redis_database: 0
upstream:
type: roundrobin
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
预览本示例所管理资源的变更,确认差异中没有意外更新或删除:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-redis
同步已审查的服务配置:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-redis
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
type: ExternalName
externalName: countries.trevorblades.com
ports:
- name: https
port: 443
targetPort: 443
---
apiVersion: apisix.apache.org/v1alpha1
kind: BackendTrafficPolicy
metadata:
namespace: aic
name: countries-graphql-https
spec:
targetRefs:
- name: countries-graphql-external-domain
kind: Service
group: ""
sectionName: https
passHost: node
scheme: https
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: graphql-limit-count-redis-plugin-config
spec:
plugins:
- name: proxy-rewrite
config:
uri: /graphql
- name: graphql-limit-count
config:
count: 2
time_window: 30
rejected_code: 429
key: remote_addr
policy: redis
redis_host: redis-standalone
redis_port: 6379
redis_password: redis-password
redis_database: 0
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: graphql-redis-limit-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /graphql-redis-limit
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: graphql-limit-count-redis-plugin-config
backendRefs:
- name: countries-graphql-external-domain
port: 443
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
ingressClassName: apisix
scheme: https
passHost: node
externalNodes:
- type: Domain
name: countries.trevorblades.com
port: 443
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: graphql-redis-limit-route
spec:
ingressClassName: apisix
http:
- name: graphql-redis-limit-route
match:
paths:
- /graphql-redis-limit
upstreams:
- name: countries-graphql-external-domain
plugins:
- name: proxy-rewrite
enable: true
config:
uri: /graphql
- name: graphql-limit-count
enable: true
config:
count: 2
time_window: 30
rejected_code: 429
key: remote_addr
policy: redis
redis_host: redis-standalone
redis_port: 6379
redis_password: redis-password
redis_database: 0
将配置应用到集群:
kubectl apply -f graphql-limit-count-ic.yaml
❶ policy: redis 将限速计数器存储在一个 Redis 服务器中。
❷ redis_host 指定上文启动的 Redis 服务。
❸ redis_port 指定 Redis 的监听端口。
❹ redis_password 使用教程中的 Redis 密码进行认证。
❺ redis_database 将计数器存储在 Redis 数据库 0 中。
向网关实例发送包含深度为 2 的 GraphQL 查询的请求:
curl -i "http://127.0.0.1:9080/graphql-redis-limit" -X POST \
-H "Content-Type: application/json" \
-d '{"query": "query { country(code: \"US\") { name } }"}'
请求应返回 200 OK,并带有 X-RateLimit-Remaining: 0。
在同一 30 秒窗口内,向另一个网关实例发送相同请求。请求应返回 429 Too Many Requests,确认这些网关节点共享配额。
使用 Redis 集群在网关实例间共享配额
以下示例展示如何在 Redis Cluster 中存储查询成本计数器,使网关节点共享经过分区和复制的计数器存储。
启动 Redis 集群
- Docker
- Kubernetes
将 GATEWAY_CONTAINER 设置为正在运行的 APISIX 或 API7 网关容器名称。创建专用网络,并将网关连接到该网络:
export GATEWAY_CONTAINER=replace-with-gateway-container-name
docker network create gateway-graphql-limit-cluster-net
docker network connect gateway-graphql-limit-cluster-net "$GATEWAY_CONTAINER"
对每个额外用于验证共享计数器的网关容器,重复执行网络连接操作:
docker network connect gateway-graphql-limit-cluster-net replace-with-additional-gateway-container
创建以下 Docker Compose 文件,配置三个主节点和三个副本:
x-redis-node: &redis-node
image: redis:8.10.2-alpine
command:
- redis-server
- --cluster-enabled
- "yes"
- --cluster-config-file
- nodes.conf
- --cluster-node-timeout
- "5000"
- --appendonly
- "no"
- --requirepass
- redis-cluster-password
- --masterauth
- redis-cluster-password
healthcheck:
test: ["CMD", "redis-cli", "-a", "redis-cluster-password", "ping"]
interval: 2s
timeout: 2s
retries: 30
networks:
- gateway-graphql-limit-cluster-net
services:
graphql-redis-cluster-1:
<<: *redis-node
container_name: graphql-redis-cluster-1
graphql-redis-cluster-2:
<<: *redis-node
container_name: graphql-redis-cluster-2
graphql-redis-cluster-3:
<<: *redis-node
container_name: graphql-redis-cluster-3
graphql-redis-cluster-4:
<<: *redis-node
container_name: graphql-redis-cluster-4
graphql-redis-cluster-5:
<<: *redis-node
container_name: graphql-redis-cluster-5
graphql-redis-cluster-6:
<<: *redis-node
container_name: graphql-redis-cluster-6
networks:
gateway-graphql-limit-cluster-net:
external: true
启动节点,并等待健康检查通过:
docker compose up -d --wait
初始化集群,为每个主节点分配一个副本:
docker exec -e REDISCLI_AUTH=redis-cluster-password graphql-redis-cluster-1 \
redis-cli --cluster create \
graphql-redis-cluster-1:6379 \
graphql-redis-cluster-2:6379 \
graphql-redis-cluster-3:6379 \
graphql-redis-cluster-4:6379 \
graphql-redis-cluster-5:6379 \
graphql-redis-cluster-6:6379 \
--cluster-replicas 1 \
--cluster-yes
输出应以 [OK] All 16384 slots covered. 结束。
等待几秒,让节点交换集群状态,然后验证所有哈希槽均可用:
docker exec -e REDISCLI_AUTH=redis-cluster-password graphql-redis-cluster-1 \
redis-cli cluster info
输出应包含 cluster_state:ok 和 cluster_slots_assigned:16384。
导出 Redis 节点地址,供网关配置使用:
export REDIS_CLUSTER_NODE_1="graphql-redis-cluster-1:6379"
export REDIS_CLUSTER_NODE_2="graphql-redis-cluster-2:6379"
export REDIS_CLUSTER_NODE_3="graphql-redis-cluster-3:6379"
export REDIS_CLUSTER_NODE_4="graphql-redis-cluster-4:6379"
export REDIS_CLUSTER_NODE_5="graphql-redis-cluster-5:6379"
export REDIS_CLUSTER_NODE_6="graphql-redis-cluster-6:6379"
创建六节点 Redis Cluster StatefulSet 和 Headless Service:
apiVersion: apps/v1
kind: StatefulSet
metadata:
namespace: aic
name: graphql-redis-cluster
spec:
serviceName: graphql-redis-cluster
replicas: 6
selector:
matchLabels:
app: graphql-redis-cluster
template:
metadata:
labels:
app: graphql-redis-cluster
spec:
containers:
- name: redis
image: redis:8.10.2-alpine
ports:
- containerPort: 6379
name: client
- containerPort: 16379
name: gossip
command:
- redis-server
- --cluster-enabled
- "yes"
- --cluster-config-file
- nodes.conf
- --cluster-node-timeout
- "5000"
- --appendonly
- "yes"
- --requirepass
- redis-cluster-password
- --masterauth
- redis-cluster-password
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
---
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: graphql-redis-cluster
spec:
clusterIP: None
selector:
app: graphql-redis-cluster
ports:
- port: 6379
name: client
- port: 16379
name: gossip
应用清单,并等待所有节点就绪:
kubectl apply -f redis-cluster.yaml
kubectl rollout status statefulset/graphql-redis-cluster -n aic
初始化集群,为每个主节点分配一个副本:
kubectl exec -n aic graphql-redis-cluster-0 \
-- env REDISCLI_AUTH=redis-cluster-password redis-cli \
--cluster create \
graphql-redis-cluster-0.graphql-redis-cluster.aic.svc:6379 \
graphql-redis-cluster-1.graphql-redis-cluster.aic.svc:6379 \
graphql-redis-cluster-2.graphql-redis-cluster.aic.svc:6379 \
graphql-redis-cluster-3.graphql-redis-cluster.aic.svc:6379 \
graphql-redis-cluster-4.graphql-redis-cluster.aic.svc:6379 \
graphql-redis-cluster-5.graphql-redis-cluster.aic.svc:6379 \
--cluster-replicas 1 \
--cluster-yes
验证集群已就绪:
kubectl exec -n aic graphql-redis-cluster-0 \
-- env REDISCLI_AUTH=redis-cluster-password redis-cli cluster info
输出应包含 cluster_state:ok 和 cluster_slots_assigned:16384。
导出 Redis 节点地址,供网关配置使用:
export REDIS_CLUSTER_NODE_1="graphql-redis-cluster-0.graphql-redis-cluster.aic.svc:6379"
export REDIS_CLUSTER_NODE_2="graphql-redis-cluster-1.graphql-redis-cluster.aic.svc:6379"
export REDIS_CLUSTER_NODE_3="graphql-redis-cluster-2.graphql-redis-cluster.aic.svc:6379"
export REDIS_CLUSTER_NODE_4="graphql-redis-cluster-3.graphql-redis-cluster.aic.svc:6379"
export REDIS_CLUSTER_NODE_5="graphql-redis-cluster-4.graphql-redis-cluster.aic.svc:6379"
export REDIS_CLUSTER_NODE_6="graphql-redis-cluster-5.graphql-redis-cluster.aic.svc:6379"
这些演示环境使用教程密码和内部服务地址。生产环境中,请限制网络访问,将凭据作为 Secret 管理,启用持久化,并配置 TLS。
创建路由
- Admin API
- ADC
- Ingress Controller
在网关集群或网关组中创建路由:
curl "http://127.0.0.1:9180/apisix/admin/routes/graphql-limit-count-route" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d @- <<EOF
{
"uri": "/graphql-cluster-limit",
"plugins": {
"proxy-rewrite": {
"uri": "/graphql"
},
"graphql-limit-count": {
"count": 2,
"time_window": 30,
"rejected_code": 429,
"key": "remote_addr",
"policy": "redis-cluster",
"redis_cluster_nodes": [
"${REDIS_CLUSTER_NODE_1}",
"${REDIS_CLUSTER_NODE_2}",
"${REDIS_CLUSTER_NODE_3}",
"${REDIS_CLUSTER_NODE_4}",
"${REDIS_CLUSTER_NODE_5}",
"${REDIS_CLUSTER_NODE_6}"
],
"redis_password": "redis-cluster-password",
"redis_cluster_name": "graphql-limit-docs-redis-cluster"
}
},
"upstream": {
"type": "roundrobin",
"pass_host": "node",
"scheme": "https",
"nodes": {
"countries.trevorblades.com:443": 1
}
}
}
EOF
创建使用 Redis 集群限速的路由:
services:
- name: graphql-redis-cluster-limit-service
labels:
docs-example: graphql-limit-cluster
routes:
- name: graphql-redis-cluster-limit-route
uris:
- /graphql-cluster-limit
plugins:
proxy-rewrite:
uri: /graphql
graphql-limit-count:
count: 2
time_window: 30
rejected_code: 429
key: remote_addr
policy: redis-cluster
redis_cluster_nodes:
- ${REDIS_CLUSTER_NODE_1}
- ${REDIS_CLUSTER_NODE_2}
- ${REDIS_CLUSTER_NODE_3}
- ${REDIS_CLUSTER_NODE_4}
- ${REDIS_CLUSTER_NODE_5}
- ${REDIS_CLUSTER_NODE_6}
redis_password: redis-cluster-password
redis_cluster_name: graphql-limit-docs-redis-cluster
upstream:
type: roundrobin
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
将导出的 Redis 节点地址渲染到 ADC 文件中:
envsubst < adc.template.yaml > adc.yaml
预览本示例所管理资源的变更,确认差异中没有意外更新或删除:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-cluster
同步已审查的服务配置:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-limit-cluster
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
type: ExternalName
externalName: countries.trevorblades.com
ports:
- name: https
port: 443
targetPort: 443
---
apiVersion: apisix.apache.org/v1alpha1
kind: BackendTrafficPolicy
metadata:
namespace: aic
name: countries-graphql-https
spec:
targetRefs:
- name: countries-graphql-external-domain
kind: Service
group: ""
sectionName: https
passHost: node
scheme: https
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: graphql-limit-count-redis-cluster-plugin-config
spec:
plugins:
- name: proxy-rewrite
config:
uri: /graphql
- name: graphql-limit-count
config:
count: 2
time_window: 30
rejected_code: 429
key: remote_addr
policy: redis-cluster
redis_cluster_nodes:
- graphql-redis-cluster-0.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-1.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-2.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-3.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-4.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-5.graphql-redis-cluster.aic.svc:6379
redis_password: redis-cluster-password
redis_cluster_name: graphql-limit-docs-redis-cluster
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: graphql-redis-cluster-limit-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /graphql-cluster-limit
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: graphql-limit-count-redis-cluster-plugin-config
backendRefs:
- name: countries-graphql-external-domain
port: 443
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: countries-graphql-external-domain
spec:
ingressClassName: apisix
scheme: https
passHost: node
externalNodes:
- type: Domain
name: countries.trevorblades.com
port: 443
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: graphql-redis-cluster-limit-route
spec:
ingressClassName: apisix
http:
- name: graphql-redis-cluster-limit-route
match:
paths:
- /graphql-cluster-limit
upstreams:
- name: countries-graphql-external-domain
plugins:
- name: proxy-rewrite
enable: true
config:
uri: /graphql
- name: graphql-limit-count
enable: true
config:
count: 2
time_window: 30
rejected_code: 429
key: remote_addr
policy: redis-cluster
redis_cluster_nodes:
- graphql-redis-cluster-0.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-1.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-2.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-3.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-4.graphql-redis-cluster.aic.svc:6379
- graphql-redis-cluster-5.graphql-redis-cluster.aic.svc:6379
redis_password: redis-cluster-password
redis_cluster_name: graphql-limit-docs-redis-cluster
将配置应用到集群:
kubectl apply -f graphql-limit-count-ic.yaml
❶ policy: redis-cluster 将限速计数器存储在 Redis Cluster 中。
❷ redis_cluster_nodes 列出上文启动的 Redis Cluster 节点。Admin API 和 ADC 示例使用为所选环境导出的地址。
❸ redis_password 使用教程中的 Redis Cluster 密码进行认证。
❹ redis_cluster_name 标识此 Redis Cluster 配置,避免网关复用另一个集群的缓存槽映射。
向网关实例发送包含深度为 2 的 GraphQL 查询的请求:
curl -i "http://127.0.0.1:9080/graphql-cluster-limit" -X POST \
-H "Content-Type: application/json" \
-d '{"query": "query { country(code: \"US\") { name } }"}'
请求应返回 200 OK,并带有 X-RateLimit-Remaining: 0。
在同一 30 秒窗口内,向另一个网关实例发送相同请求。请求应返回 429 Too Many Requests,确认这些网关节点共享配额。