---
title: GraphQL 分页与缓存(Relay Cursor、Cache Key 与字段策略)
keywords:
- GraphQL
- Relay
- Cursor 分页
- 缓存键
- Apollo 缓存
description: 基于 Relay Cursor 模式实现稳定分页,结合客户端缓存的字段策略与键设计,提升一致性与性能并提供验证方法。
date: 2025-11-26
categories:
- 文章资讯
- 技术教程
---
GraphQL 分页与缓存(Relay Cursor、Cache Key 与字段策略)
概述
Cursor 模式避免 Offset 的翻页偏移与数据插入影响。客户端缓存需要合理的 key 与字段合并策略。
关键实践与参数
- Relay 连接模型:
edges、node、pageInfo{ hasNextPage, endCursor }。 - Cursor 生成:稳定且单调;避免暴露自增 ID,可使用时间戳或哈希。
- 客户端缓存:
- Apollo
typePolicies使用keyArgs: ["query", "filters"]与自定义merge。 - 对
edges合并去重,按cursor拼接。
示例(Apollo 客户端)
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
articles: {
keyArgs: ["filters"],
merge(existing = { edges: [] }, incoming) {
const map = new Map()
for (const e of [...existing.edges, ...incoming.edges]) {
map.set(e.cursor, e)
}
return { ...incoming, edges: Array.from(map.values()) }
}
}
}
}
}
})
验证方法
- 插入新数据并在分页边界观察是否重复或漏项。
- 压测滚动加载与缓存命中情况;统计网络请求减少比例。
- 对比 Offset 与 Cursor 的一致性与性能差异。
注意事项
- Cursor 不应可预测;避免越权遍历。
- 缓存键需包含过滤条件;避免不同查询污染同一列表。
- 后端需保证按排序字段生成稳定游标。

发表评论 取消回复