配置 GraphQL 代理
API7 网关可以像代理其他 HTTP API 一样代理 GraphQL 流量。在支持 GraphQL 感知插件的环境中,你还可以应用 GraphQL 专用的限流和缓存策略。
前置条件
- API7 企业版实例正在运行。
- 已创建网关组,并且网关实例正在运行。
- 从控制台获取令牌。
基础 GraphQL 代理
从一个标准 HTTP 路由开始,将 GraphQL 请求转发到上游。
以下示例使用 https://countries.trevorblades.com/ 作为上游。代理到要求使用自身主机名的 HTTPS 上游时,请设置 scheme: https 和 pass_host: node。
- ADC
- Admin API
adc.yaml
services:
- name: graphql-service
upstream:
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
routes:
- name: graphql-route
uris:
- /graphql
methods:
- POST
adc sync -f adc.yaml
# 1. 为 GraphQL 上游创建服务
curl -k "https://localhost:7443/apisix/admin/services/graphql-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "graphql-service",
"upstream": {
"type": "roundrobin",
"scheme": "https",
"pass_host": "node",
"nodes": [
{
"host": "countries.trevorblades.com",
"port": 443,
"weight": 1
}
]
}
}'
# 2. 为服务创建路由
curl -k "https://localhost:7443/apisix/admin/routes/graphql-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "graphql-route",
"paths": ["/graphql"],
"methods": ["POST"],
"service_id": "graphql-service"
}'
在本地验证环境中,基础 Admin API 示例在使用 scheme: https 和 pass_host: node 配置上游后,可以端到端正常工作。
GraphQL 限流
graphql-limit-count 插件基于查询深度提供 GraphQL 感知的限流能力。
配置 GraphQL 限流
在代理到 GraphQL 上游的路由上启用 graphql-limit-count 插件。该插件仅支持 POST 方法。
除了 count、time_window、key_type 和 key 外,该插件还需要其他字段。至少需要包含 policy。例如,本地策略使用 policy: local。
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/routes/graphql-limit-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "graphql-limit-route",
"paths": ["/graphql"],
"service_id": "graphql-service",
"methods": ["POST"],
"plugins": {
"graphql-limit-count": {
"count": 6,
"time_window": 60,
"rejected_code": 429,
"policy": "local",
"key_type": "var",
"key": "remote_addr"
}
}
}'
adc.yaml
services:
- name: graphql-limit-service
upstream:
scheme: https
pass_host: node
nodes:
- host: countries.trevorblades.com
port: 443
weight: 1
routes:
- name: graphql-limit-route
uris:
- /graphql
methods:
- POST
plugins:
graphql-limit-count:
count: 6
time_window: 60
rejected_code: 429
policy: local
key_type: var
key: remote_addr
adc sync -f adc.yaml