扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
发现1000+提升效率与开发的AI工具和实用程序:https://tools.cmdragon.cn/
使用 Strawberry 库实现 GraphQL 服务:
# 安装依赖:strawberry-graphql==0.215.3 fastapi==0.103.1
from fastapi import FastAPI
import strawberry
from strawberry.asgi import GraphQL
@strawberry.type
class User:
id: int
name: str
@strawberry.type
class Query:
@strawberry.field
async def user(self, id: int) -> User:
# 模拟数据库查询
return User(id=id, name=f"User{id}")
schema = strawberry.Schema(query=Query)
app = FastAPI()
app.add_route("/graphql", GraphQL(schema))
Thinking...
优化策略:
# 安装依赖:prometheus-client==0.17.1
from prometheus_client import Counter, Histogram
from fastapi import Request
GRAPHQL_QUERY_COUNTER = Counter(
"graphql_queries_total",
"Total number of GraphQL queries",
["operation"]
)
GRAPHQL_DURATION = Histogram(
"graphql_request_duration_seconds",
"Time spent processing GraphQL requests",
["operation"]
)
@app.middleware("http")
async def monitor_requests(request: Request, call_next):
start_time = time.time()
operation_name = request.state.graphql_operation.get("name", "unknown")
with GRAPHQL_DURATION.labels(operation=operation_name).time():
response = await call_next(request)
GRAPHQL_QUERY_COUNTER.labels(operation=operation_name).inc()
return response
指标名称 | 类型 | 描述 |
---|---|---|
graphql_queries_total | Counter | 按操作类型统计的查询次数 |
graphql_errors_total | Counter | 按错误类型统计的异常次数 |
graphql_resolve_time | Histogram | 字段解析耗时分布 |
# 安装依赖:elastic-apm==6.15.2
from elasticapm.contrib.starlette import make_apm_client
apm = make_apm_client({
"SERVICE_NAME": "fastapi-graphql",
"SERVER_URL": "http://apm-server:8200",
"ENVIRONMENT": "production"
})
app.add_middleware(ElasticAPM, client=apm)
from elasticapm import capture_span
@strawberry.field
async def user(self, info, id: int) -> User:
with capture_span("user_query", "database"):
# 执行数据库查询
return await fetch_user(id)
from strawberry.extensions import QueryDepthLimiter
app.add_route("/graphql", GraphQL(
schema,
extensions=[
QueryDepthLimiter(max_depth=10)
]
))
from elasticapm import capture_exception
@app.exception_handler(GraphQLError)
async def handle_graphql_errors(request, exc):
capture_exception()
return PlainTextResponse(str(exc), status_code=500)
如何防止 GraphQL 查询的 N+1 问题?
A. 使用 DataLoader 批处理机制
B. 限制查询深度
C. 增加服务器线程数
(答案:A。解析:DataLoader 可以将多个请求合并为批量查询)
哪个 Prometheus 指标类型适合记录响应时间分布?
A. Counter
B. Gauge
C. Histogram
(答案:C。解析:Histogram 类型支持分位数计算)
错误 1:422 Unprocessable Entity
错误 2:N+1 Query Problem
graph LR A[客户端] --> B[FastAPI服务] B --> C[数据采集] C --> D[数据存储] D --> E[可视化展示]
pip install fastapi==0.103.1 strawberry-graphql==0.215.3
pip install prometheus-client==0.17.1 elastic-apm==6.15.2
余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
,阅读完整的文章:如何在 FastAPI 中玩转 GraphQL 性能监控与 APM 集成?
参与评论
手机查看
返回顶部