配置 GraphQL 代理
API7 网关可以像代理其他 HTTP API 一样代理 GraphQL 流量。在支持 GraphQL 感知插件的环境中,你还可以应用 GraphQL 专用的限流和缓存策略。
前置条件
- API7 企业版实例正在运行。
- 已创建网关组,并且网关实例正在运行。
- 从控制台获取 Token。
基础 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
labels:
docs-example: graphql-service
预览本示例管理的资源变更,确认没有非预期的更新或删除:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-service
审查变更后同步配置:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=graphql-service
# 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-proxy-cache 替换 graphql-limit-count。