Cabloy/Zova 与 Next.js 的前端缓存差异

0 阅读8分钟

Zova 缓存的是"状态",Next.js 缓存的是"渲染输出"。两者不是同一件事的两种写法,而是两个不同问题域的答案。

聊缓存时最容易犯的错,是"默认它们在解决同一个问题"。

Zova 和 Next.js 都有缓存,但起点完全不同:

  • Zova 的缓存是给 Vue SPA + SSR 用的——核心问题是"用户关掉浏览器重开,之前看到的订单列表还在不在"、"登录 A 看到的数据,登出登录 B 后能不能自动清干净"。它是客户端状态持久化层。
  • Next.js 的缓存是给 React 全栈 SSR/SSG 用的——核心问题是"这个路由页面能不能预渲染好直接返回,不用每次都跑一遍 React"、"fetch 结果能不能跨请求复用"。它是渲染性能优化层。

所以对比两边的缓存实现,不能只看 API 名字有没有对得上,要看它们各自服务的那个问题。

下面从 Zova 的实现开始,先看清它到底缓存了什么、为什么要缓存,再拉 Next.js 过来并排看。


一、Zova 的 5 层缓存架构

Zova 的缓存藏在一个叫 a-model 的模块里——也就是 Model 层。入口在 storage.ts 的 moduleLoaded():

async moduleLoaded() {
  const options = deepExtend({}, this.scope.config.queryClientConfig.defaultOptions);
  if (process.env.SERVER) {
    options.queries ??= {};
    options.queries.gcTime = Infinity;   // SSR 期间不自动 GC
  }
  const queryCache = new QueryCache();
  const queryClient = new QueryClient({ defaultOptions: options, queryCache });
  this._persistence = new ModelPersistenceContext(queryClient, this.sys.env.SITE_ID);
  this.app.vue.use(VueQueryPlugin, { queryClient });
}

基础设置来自 config.ts:

const defaultOptions = {
  queries: {
    retry: false,
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchOnReconnect: true,
    gcTime: 1000 * 60 * 5,   // 默认 5 分钟
  },
  dehydrate: {
    shouldDehydrateQuery(query) {
      if (query.meta?.ssr?.dehydrate === false) return false;
      if (typeof query.meta?.persister === 'object' && query.meta?.persister?.sync) return false;
      return defaultShouldDehydrateQuery(query);
    },
    shouldDehydrateMutation(_mutation) { return false; },
  },
};

把整个架构拆开看,是这样 5 层:

Layer 1: 内存层 — TanStack Vue Query QueryCache
  单次应用生命周期内的查询结果缓存
  默认 gcTime: 5min, refetchOnWindowFocus: false
  SSR 时 gcTime: Infinity

Layer 2: 持久化层 — Query Persister
  cookie: 会话级 (session cookie)
  localStorage: 永久 (Infinity)
  localforage/IndexedDB: 24h 默认 maxAge
  配套 PersistenceQueue: 异步写入串行化 + generation 防竞态

Layer 3: 身份隔离 — ModelPersistenceContext
  scope = [instanceId, siteId, userId]
  scope 变化 → epoch++ → 自动 invalidate 所有 DB 持久化查询
  epoch token: 过期操作自动 CancelledError 放弃

Layer 4: SSR 响应缓存 — HTTP Cache-Control
  profile 'public': Cache-Control: public, max-age=N
  profile 'session': Cache-Control: private, no-store

Layer 5: 页面组件缓存 — Router Tabs KeepAlive
  tabsOptions.cache: true → localStorage 持久化标签页状态
  Vue KeepAlive: 组件实例缓存

这 5 层里,真正有 Zova 特色的是 2、3、5——因为那三层在 Next.js 里要么不存在,要么是完全不同的实现逻辑。


二、持久化层:不是可选插件,是核心能力

Zova 的持久化能力完全自己实现了一遍,没有直接用 @tanstack/query-persist-client,而是做了一层包装,加了 generation 机制。核心在 bean.model.persister.ts。

开发者声明持久化的方式很简单:

// Zova: 在 Model Bean 里声明
@Model()
export class ModelUserInfo extends BeanModelBase {
  $userInfo = this.$useQuery({
    queryKey: ['userInfo'],
    queryFn: () => api.getUserInfo(),
    meta: {
      persister: { storage: 'db' }  // IndexedDB 持久化
    }
  });
}

三级存储由 storage 选项决定,默认值来自 config.ts:

persister: {
  maxAge: {
    cookie: undefined,    // undefined = session cookie
    local: Infinity,      // localStorage 永久
    db: 1000 * 60 * 60 * 24,  // IndexedDB 24h
  },
  refetchOnRestore: true,
},

真正的存储选择在 _getPersisterStorage() 里:

protected _getPersisterStorage(options, query) {
  if (options.storage === 'cookie') return CookieWrapper;
  if (process.env.SERVER) return undefined;   // SSR 不持久化到浏览器
  if (options.storage === 'local') return localStorage;
  if (options.storage === 'db') return localforage;
}

值得注意的是 SSR 分支:服务端渲染时不写浏览器存储,这和 Next.js SSR 时 fetch 走自己的 Data Cache 完全不一样。Zova 的 SSR 数据走的是 dehydrate/hydrate 通道——服务端渲染完,把 QueryCache 序列化进 HTML,客户端水合时恢复。

PersistenceQueue:异步写入的防竞态装置

持久化层里最精巧的设计是 persistenceQueue.ts。

IndexedDB 是异步的,setItem/removeItem 会排队。如果"写 A → 删 A → 写 B"乱序执行,就会出问题。Zova 用 generation 解决:

export class PersistenceQueue {
  private _generation = 0;
  private _keyGenerations = new Map<string, number>();

  generation(key: string): string {
    return `${this._generation}:${this._keyGenerations.get(key) ?? 0}`;
  }

  invalidate(key: string) {
    this._keyGenerations.set(key, (this._keyGenerations.get(key) ?? 0) + 1);
  }

  invalidateAll() {
    this._generation++;
    this._keyGenerations.clear();
  }
  // ...
}

工作流程:

  1. 每次对某个 key 做 save/remove 之前,先 queue.invalidate(key),这个 key 的 generation 数字 +1。
  2. 异步操作实际执行时,检查 generation 是否和排队时一致。
  3. 中间有新的写入请求,旧操作的 generation 就过期了,自动跳过。
// bean.model.persister.ts _persisterSave()
const storageKey = this._getPersisterStorageKey(options, query);
const queue = getPersistenceQueue(storage);
queue.invalidate(storageKey);   // 先作废旧 generation
// 然后排队写入...

这保证了"最新的写入才是有效的",解决了 IndexedDB 异步读写顺序错乱的问题。Next.js 的 Router Cache 和 Data Cache 都是进程内内存,不存在这个问题。


三、身份隔离:scope + epoch token

这是 Zova 独有的机制——Next.js 完全不涉及多租户,所以没这个需求。

modelPersistence.ts 里定义了核心数据结构:

export type ModelPersistenceScope = readonly [string | null, string | null, string | null];
//                                 [instanceId, siteId, userId]

export interface ModelPersistenceToken {
  readonly scope: ModelPersistenceScope;
  readonly epoch: number;
}

scope 是三元组 [instanceId, siteId, userId]。当用户身份切换时——登出、登录另一个账号、切换工作空间——scope 就变了。

自动失效的完整流程在 update() 方法里:

update(values, options = {}) {
  const scope = Object.freeze([
    normalize(values.instanceId),
    normalize(values.siteId),
    normalize(values.userId),
  ]);
  if (scope.every((v, i) => v === this._scope[i])) {
    this._hydrated.clear();
    return;
  }
  // 找到所有需要失效的查询:meta.persister.storage === 'db' 的
  const affected = this._queryClient
    .getQueryCache().getAll()
    .filter(query => isModelPersistenceDb(query.meta?.persister) && !(adopt && this._hydrated.has(query)));
  this._scope = scope;
  this._hydrated.clear();
  this._invalidate(affected);
  // 静默 refetch active queries
  if (options.refetchActive === false) return;
  void Promise.resolve().then(() => {
    if (this.current(token)) {
      return this._queryClient.refetchQueries({
        type: 'active',
        predicate: query => affected.includes(query),
      });
    }
  });
}

_invalidate() 做了什么?

private _invalidate(queries: Query[]) {
  this._epoch++;
  // 先取消所有正在 retry 的查询(silent: true 防止旧错误发布)
  for (const query of queries) void query.cancel({ silent: true, revert: false });
  notifyManager.batch(() => {
    for (const query of queries) {
      query.setOptions({ initialData: undefined, initialDataUpdatedAt: undefined });
      for (const observer of query.observers) {
        observer.setOptions({ initialData: undefined, placeholderData: undefined });
      }
      query.setState(emptyQueryState());
    }
  });
  this._version.value++;
  const token = this.capture();
  for (const listener of this._listeners) listener(token);
}

关键点:先 cancel 所有,再 批量重置所有 observer 的 initialData/placeholderData,最后 把 query.state 整体清空。

epoch token:过期操作静默丢弃

这一层保证了"scope 变更瞬间,所有在途操作自动作废"。每个持久化的读/写/删除操作都先 capture 一个 token,执行完再检查:

// bean.model.persister.ts _createDbPersister()
const token = persistence.capture();
// ... 执行异步操作 ...
// 操作完成后检查
if (options.storage !== 'db' || persistence.current(token)) {
  // scope 没变,结果有效
} else {
  // scope 变了 → 静默丢弃结果
}

current(token) 检查两件事:epoch 没变,scope 没变。任何一个变了就返回 false。

这比 Next.js 手动调用 revalidatePath / revalidateTag 优雅多了——在 Next.js 里,你需要在每次用户登出/登录后手动触发失效,而且失效只影响服务器端缓存。Zova 是 scope 变更自动联动所有 DB 持久化查询,同时取消在途操作,防止旧数据回写到新身份的存储。

存储 Key 也是 scope-aware 的

_getPersisterStorageKey() 里:

return options.storage === 'db'
  ? getModelPersistenceStorageKey(
      this.sys.env.APP_NAME ?? '',
      (token ?? this.$modelPersistence.capture()).scope,
      logicalKey,
    )
  : logicalKey;

生成的 key 格式:["zova-model-db", 1, appName, scope, logicalKey]。scope 编码进了 key 本身,所以 IndexedDB 里不同身份的查询数据天然隔离,即使手动遍历也不会混淆。


四、SSR 缓存:显式 profile 声明

Zova 的 SSR 缓存策略在 ssrProfile.ts 和 ssrHandler.ts 里:

// ssrProfile.ts
export function resolveSsrProfile(routeProfile, defaultProfile) {
  const ssrProfile = routeProfile ?? defaultProfile ?? 'public';
  if (ssrProfile !== 'public' && ssrProfile !== 'session') {
    throw new Error(`invalid SSR profile: ${ssrProfile}`);
  }
  return ssrProfile;
}

只有两档:public 和 session。响应头设置也很直接:

// ssrHandler.ts
if (ssrProfile === 'session') {
  options.res.setHeader('cache-control', 'private, no-store');
}
// ...
if (ssrProfile === 'public') {
  const expires = resolveSsrResponseCacheExpires(ssrProfileOptions.responseCache, this.sys.env.META_MODE);
  if (expires === 0) {
    res.setHeader('cache-control', 'no-cache, no-store, must-revalidate');
  } else {
    res.setHeader('cache-control', `public, max-age=${expires}`);
  }
}

开发环境有特殊处理:metaMode === 'development' 时强制 expires = 0,即 no-cache, no-store, must-revalidate——防止开发时浏览器缓存干扰。

Zova 的 SSR 缓存策略是手动声明式的——每个路由通过 ssrProfile: 'public' | 'session' 决定,不做自动推断。和 Next.js App Router 的自动推断形成鲜明对比:App Router 会检查你有没有用 cookies、headers、searchParams 这些动态 API,有的话自动把路由从 Full Route Cache 里排除。


五、拉 Next.js 过来并排看

现在把 Next.js 的三层缓存摆过来。App Router 的架构文档很清楚:

Next.js App Router 缓存架构
Layer 1: Request Memoization (React)
  React 组件树内的 fetch GET/HEAD 自动去重
  生命周期:单次 request
  范围:只在 React Component Tree 里

Layer 2: Data Cache (Next.js 内置)
  fetch 结果跨请求、跨部署持久化
  默认:no-store(不缓存)
  进入方式:cache: 'force-cache' 或 next.revalidate > 0
  时间驱动:stale-while-revalidate
  事件驱动:revalidateTag / revalidatePath

Layer 3: Full Route Cache (Next.js 内置)
  HTML + RSC Payload 预渲染输出
  构建时 / ISR 触发时生成
  失效条件:Data Cache revalidate / redeploy
  自动退出:使用 cookies/headers/searchParams 动态 API

Layer 4: Router Cache (浏览器内存)
  客户端 RSC Payload 缓存
  周期:session + 自动过期
  粒度:layout / loading / page 分段

三层对比

维度Zova (Vue 前端)Next.js (React 全栈)
缓存层级5 层:内存 + 持久化 + 身份隔离 + SSR HTTP + KeepAlive4 层:Memoization + Data Cache + Full Route + Router Cache
持久化存储Cookie / localStorage / IndexedDB无(浏览器 BFCache + 服务器内存/磁盘)
持久化默认值非 DB 查询内存;DB 查询 IndexedDB (24h)默认内存
身份隔离✅ scope=[iid,siteId,userId] epoch token❌ 不涉及
SSR 数据传递QueryCache dehydrate → window.INITIAL_STATE_DEFERRSC Payload → React reconciliation
SSR 缓存策略显式 profile 声明 public/sessionfetch 选项 + Route Segment Config 自动推断
异步安全PersistenceQueue generation + CancelledError silentSWR 后台刷新
失效触发scope 变更自动 invalidate + epoch++revalidateTag / revalidatePath / 手动

TTL 策略的本质差异

Zova 的 TTL 是 maxAge——过期就丢。Next.js 的 revalidate: N 是 stale-while-revalidate——过期后先返回旧数据,后台静默刷新。

ZovaNext.js
时间语义数据寿命服务器不主动刷新的最长时间
过期后直接丢弃,下次 fetch仍返回旧数据,后台触发刷新
对用户的影响过期后第一次请求会 loading过期后第一次请求立即有响应
典型场景用户敏感数据(Auth Token、验证码)低敏感数据(博客文章、商品列表)

默认行为的差异

Zova 的默认配置里 refetchOnMount: false、refetchOnWindowFocus: false、gcTime: 5min——倾向于尽量少请求,靠缓存顶住。

Next.js 的 fetch 默认 cache: 'no-store'——倾向于每次都请求,开发者显式 opt-in 才进 Data Cache。

这两个默认值的方向完全相反,背后的设计判断也相反:

  • Zova 默认"信任缓存":因为是 SPA,用户对"页面不刷新但数据在"有预期。缓存失效由开发者精确控制(scope 变更、手动 invalidate)。
  • Next.js 默认"不信任缓存":因为是全栈渲染,默认要保证数据新鲜。缓存是开发者显式 opt-in 的优化手段,不是默认行为。

六、Zova 特有的三个缓存细节

1. 服务端渲染期间把 gcTime 设成 Infinity

if (process.env.SERVER) {
  options.queries ??= {};
  options.queries.gcTime = Infinity;
}

这意味着 SSR 渲染期间 永远不自动 GC。原因很简单:服务端渲染时 QueryCache 里的查询结果最终会被 dehydrate 进 HTML,客户端恢复后它们才重新参与生命周期。如果 SSR 期间某个查询被 GC 了,dehydrate 出来的缓存就缺了一条。

Next.js 没有这个问题——服务端每次渲染都是独立的,Data Cache 是进程级独立存储,和渲染生命周期解耦。

2. hydrate 期间的 staleTime 特殊处理

在 $useQuery() 里:

const sync = typeof options.meta?.persister === 'object' && options.meta?.persister?.sync;
if (sync !== true) {
  const staleTime = options.staleTime ?? this.scopeSelf.config.query.staleTime.async;
  const queryCache = this.$queryFind({ queryKey });
  const queryCacheExists = queryCache?.state.data !== undefined;
  options.staleTime = query => {
    if (!queryCacheExists) return resolveStaleTime(0, query);
    if (process.env.CLIENT && this.ctx.meta.$ssr.isRuntimeSsrPreHydration) {
      return resolveStaleTime(this.scopeSelf.config.query.staleTime.ssr, query);  // Infinity
    }
    return resolveStaleTime(staleTime, query);
  };
}

staleTime.ssr 默认值是 Infinity——水合期间,从 SSR dehydrate 恢复的查询被认为 永远不过期。因为服务端刚渲染完的数据,客户端水合时没有理由不相信。水合完成后才恢复正常的 staleTime.async(默认 0,即立即认为 stale)。

Next.js 不需要这个——客户端 RSC Payload 里已经包含了 dataUpdatedAt 时间戳,React Query 自行判断新鲜度。

3. Router Tabs 持久化

这是一个很实用的场景。tabs.ts 里:

@Model<IModelOptionsTabs>({ cache: false })
export class ModelTabs extends BeanModelBase {
  tabsOptions: ModelTabsOptions;

  protected async __init__(scene: string, options?: ModelTabsOptions) {
    // ...
    if (this.tabsOptions.cache) {
      this._tabsState = this.$useStateLocalAsync(queryOptionsTabs);  // localStorage 持久化
      this._offPersistence = persistence.subscribe(() => {
        if (!this._tabsDisposed && !this.ctx.disposed) {
          this._startTabsRestore(this._getTabsReadiness());
        }
      });
    } else {
      this._tabsState = this.$useStateMem(queryOptionsTabs);  // 纯内存
    }
  }
}

tabsOptions.cache: true 时,标签页列表持久化到 localStorage。但持久性不是直接用,还要等身份匹配:persistence.subscribe() 监听 scope 变更,每次 scope 变了就触发从持久化重新加载,确保标签页状态和当前身份对齐。

Next.js Router Cache 里虽然也缓存了路由段状态,但不跨 session 持久化,也没有身份感知的自动恢复。浏览器关了重开,之前打开的标签页就没了。


七、本质判断

把所有差异收束成一句话:

Zova 缓存"数据状态",Next.js 缓存"渲染输出"。

Zova 关心的是:

  • 浏览器关掉重开,之前看到的订单列表还在不在?
  • 用户登出后,另一个账号会不会看到残留数据?
  • 同一个用户换个工作空间,缓存要不要清?

Next.js 关心的是:

  • 这个路由页面是不是预渲染过了?能不能跳过服务端?
  • fetch 结果能不能跨请求复用?
  • Headless CMS 更新了,哪个 tag 要失效?

前者是客户端架构的思考——多租户 SPA 怎么管理状态生命周期。后者是全栈渲染框架的思考——怎么减少 server work、加速首屏。

两者在同一个应用中可以共存:后端用 Zova 的身份隔离 + 持久化保住用户状态;SSR 层如果用 Next.js 的话,靠 ISR + revalidateTag 保住渲染输出。它们不冲突,反而互补。


八、小结

  1. Zova 的缓存架构是 5 层:内存 → 持久化 → 身份隔离 → SSR HTTP → KeepAlive。核心是持久化和身份隔离两层。
  2. 持久化层自己实现了 PersistenceQueue + generation 机制来防止异步竞态。三级存储(cookie / localStorage / IndexedDB)按 maxAge 过期。
  3. 身份隔离层用 scope 三元组 + epoch token 做到身份变更时自动 invalidate 所有 DB 持久化查询,在途操作静默丢弃。
  4. SSR 缓存策略是显式两档 profile(public / session),不做自动推断。
  5. Next.js 的缓存是 4 层叠加,围绕渲染输出复用设计。TTL 语义是 stale-while-revalidate,默认不信任缓存。
  6. 两个框架的默认行为方向相反:Zova 默认信任缓存、少请求;Next.js 默认不信任、显式 opt-in 才缓存。
  7. 两者不冲突,可以在同一个应用中共存互补。

参考与源码

Zova / Cabloy

Next.js