N Next.js 中文
原文 ↗

cacheHandlers

在 Next.js 中为 use cache 指令配置自定义缓存处理器。

更新于 2026-10-15Next.js 16.4.6

cacheHandlers 配置允许你为 'use cache' 和 'use cache: remote' 定义自定义缓存存储实现。这使你可以将缓存的组件和函数存储在外部服务中,或自定义缓存行为。'use cache: private' 不可配置。

何时使用自定义缓存处理器

大多数应用不需要自定义缓存处理器。 默认的内存缓存适用于典型用例。

自定义缓存处理器适用于高级场景,例如你需要在多个实例之间共享缓存,或更改缓存的存储位置。例如,你可以为外部存储(如键值存储)配置自定义的 remote 处理器,然后在代码中使用 'use cache' 进行内存缓存,并使用 'use cache: remote' 进行外部存储,从而在同一应用中采用不同的缓存策略。

跨实例共享缓存

默认的内存缓存隔离于每个 Next.js 进程。如果你运行多个服务器或容器,每个实例都会有自己独立的缓存,不会与其他实例共享,并且在重启时会丢失。

自定义处理器让你可以集成所有 Next.js 实例都能访问的共享存储系统(如 Redis、Memcached 或 DynamoDB)。

更改存储类型

你可能希望以不同于默认内存方案的方式存储缓存。你可以实现一个自定义处理器,将缓存存储在磁盘、数据库或外部缓存服务中。原因包括:在重启后保持持久化、减少内存占用,或与现有基础设施集成。

用法

要配置自定义缓存处理器:

  1. 在单独的文件中定义你的缓存处理器,有关实现细节,请参阅示例。
  2. 在 Next 配置文件中引用该文件路径

TypeScript

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheHandlers: {
    default: require.resolve('./cache-handlers/default-handler.js'),
    remote: require.resolve('./cache-handlers/remote-handler.js'),
  },
}

export default nextConfig

JavaScript

next.config.jsjs
module.exports = {
  cacheHandlers: {
    default: require.resolve('./cache-handlers/default-handler.js'),
    remote: require.resolve('./cache-handlers/remote-handler.js'),
  },
}

处理器类型

  • default:由 'use cache' 指令使用
  • remote:由 'use cache: remote' 指令使用

如果你没有配置 cacheHandlers,Next.js 会为 default 和 remote 使用内存 LRU(最近最少使用)缓存。你可以查看默认实现作为参考。

你也可以定义额外的具名处理器(例如 sessions、analytics),并使用 'use cache: <name>' 引用它们。

请注意,'use cache: private' 不使用缓存处理器,且无法自定义。

CacheEntry 类型

缓存处理器存储并返回 CacheEntry 对象。该类型和 CacheHandler 都从 next/cache 导出:

import type { CacheHandler, CacheEntry } from 'next/cache'

条目具有以下结构:

interface CacheEntry {
  value: ReadableStream<Uint8Array>
  tags: string[]
  stale: number
  timestamp: number
  expire: number
  revalidate: number
}
属性 类型 描述
value ReadableStream<Uint8Array> 缓存的数据,以一次性流的形式提供。
tags string[] 缓存标签(不包括软标签)。
stale number 客户端失效的持续时间(秒)。
timestamp number 条目的创建时间(以毫秒为单位的时间戳)。
expire number 条目允许被使用的时长(秒)。
revalidate number 距离条目应重新验证的时长(秒)。

条目值流

每个处理器都通过 set() 写入条目,并通过 get() 提供条目。这两种方法都操作条目的序列化值,该值以 ReadableStream<Uint8Array> 的形式传入。该流有两个特性会约束每一种实现:

  • 它只能被读取一次。 请在 set() 中消费它,并在每次 get() 时基于已存储的数据构建一个新的流。已被读取的流无法服务于第二个读取者:它不会提供任何数据,或者如果第一个读取者仍持有其锁,则会抛出异常。
  • 它归属于产生该条目的那个请求。 一旦 set() 完成解析,就不要保留它。该流持有对该请求的引用,因此保留它会让该请求的内存一直被占用,直到你的条目被逐出。pendingEntry promise 同样如此。Next.js 会为渲染保留自己的一份值副本,因此你的处理器可以自由消费它接收到的流。

如何持久化数据由你决定。缓冲整个流,以及在数据块到达时将其管道传输到你的存储,都是可行的,只要你恰好消费它一次。大型条目值得使用管道:一个页面可能序列化成大量字节,而类 S3 的后端可以接收它们,而无需你的处理器持有第二份副本。

还有两种需要提前考虑的情况:

  • 扇出(Fan-out)。 如果单个条目必须送达两个目的地,例如本地存储和远程存储,请使用 .tee(),并在 set() 完成解析之前消费两个分支。分流(Teeing)并不是保留该值的办法。已存储的分支确实能服务于下一次读取,但它会持有源流、其缓冲的数据块以及产生它们的请求,而这些都不会体现在你的存储所统计的大小中。
  • 中断的值。 流可能在渲染过程中途出错,导致你持有一个不完整的值。你需要决定是保留还是丢弃它。丢弃更安全,因为不完整的值会产生不完整的页面。这与部分写入的存储条目不同,后者由 错误处理 涵盖。

API 参考

缓存处理器必须实现 CacheHandler 接口,包含以下五个方法。

set()

为给定的缓存键存储缓存条目。

set(cacheKey: string, pendingEntry: Promise<CacheEntry>): Promise<void>
参数 类型 描述
cacheKey string 用于存储该条目的唯一键。
pendingEntry Promise<CacheEntry> 一个会解析为缓存条目的 Promise。

返回 Promise<void>。

调用 set() 时条目可能仍在生成中,因此请先 await pendingEntry。然后消费值流并持久化其传递的内容,如条目值流中所述。

下面的示例采用缓冲,这是更简单的选项,也是内存存储的合适选择。远程处理器则可以将 entry.value 通过管道传输到上传目标。

const cacheHandler = {
  async set(cacheKey, pendingEntry) {
    // Wait for the entry to be ready
    const entry = await pendingEntry

    // Consume the stream, then keep the data rather than the stream
    const value = new Uint8Array(await new Response(entry.value).arrayBuffer())

    // Store in your cache system
    cache.set(cacheKey, { ...entry, value })
  },
}

get()

检索给定缓存键对应的缓存条目。

get(cacheKey: string, softTags: string[]): Promise<CacheEntry | undefined>
参数 类型 描述
cacheKey string 缓存条目的唯一键。
softTags string[] 从路由路径派生出的隐式标签。有关如何使用它们,请参阅软标签。

如果存储了 CacheEntry 对象则返回该对象,否则返回 undefined。

你的 get 方法应从存储中检索缓存条目,并在没有存储任何内容时返回 undefined。

你无需检查条目的新旧程度。Next.js 在每次读取时都会将 timestamp 与条目自身的 expire 进行比较,并将过旧的条目视为未命中。当结果即将写入另一个服务器缓存时,它会对 revalidate 应用相同的检查;并且在开发服务器上会稍微延长条目的保留时间,以保持重新加载的速度。你自己的时效检查只是重复了其中的第一项。

这两个时间对你的意义在于 Next.js 会如何处理你返回的条目:

  • 超过 expire 后,条目会被丢弃并重新生成值。
  • 超过 revalidate 但仍在 expire 之内时,会提供该条目并在后台生成新的条目。

提前丢弃条目是一种策略选择,而非硬性要求。内置处理器会在 revalidate 时丢弃,因为当内存中的条目很可能在任何读取之前就被驱逐时,预热替代条目是徒劳的。共享存储没有这个问题,可以一直提供到 expire。

不过,驱逐由你负责。Next.js 从不从你的存储中删除条目,因此请使用一种能回收不再被读取的条目的机制:基于 expire 的 TTL,或像内置处理器中那样的大小受限 LRU。在提供条目时检查其时效并不是驱逐,因为它只会触及仍在被读取的键。

失效与这两个时间都无关。当某个标签告诉你条目已过期时,你有两个选择:

  • 返回 undefined。该条目会被视为缺失,Next.js 会立即重新生成它。
  • 返回带有 revalidate: -1 的条目。Next.js 会提供该条目并在后台重新生成,因为负的 revalidate 总是位于过去。

有关这些失效的来源,请参阅软标签和分布式标签协调。

每次命中时,都要将存储的数据包装到一个新的流中,而不要使用你在 set() 中收到的那个流。

const cacheHandler = {
  async get(cacheKey, softTags) {
    const entry = cache.get(cacheKey)
    if (!entry) return undefined

    // No age check: Next.js compares `timestamp` against `expire` itself.
    // `entry.value` holds the stored bytes, so wrap them in a fresh stream
    return {
      ...entry,
      value: new ReadableStream({
        start(controller) {
          controller.enqueue(entry.value)
          controller.close()
        },
      }),
    }
  },
}

refreshTags()

每个请求调用一次,在此类处理程序的第一次缓存读取之前调用,以便处理程序能从外部服务同步标签状态。

refreshTags(): Promise<void>

返回 Promise<void>。

对于内存缓存,这可以是空操作。对于分布式缓存,请用它从外部服务或数据库读取标签状态,以便此实例在从自己的存储中提供任何内容之前,先了解其他实例所做的失效操作。如果一个请求没有从此处理程序读取任何内容,则永远不会调用它。

const cacheHandler = {
  async refreshTags() {
    // For in-memory cache, no action needed
    // For distributed cache, sync tag state from external service
  },
}

getExpiration()

获取一组标签的最大重新验证时间戳。

getExpiration(tags: string[]): Promise<number>
参数 类型 描述
tags string[] 要检查过期情况的标签数组。

返回:

  • 如果这些标签从未被重新验证过,则返回 0
  • 表示最近一次重新验证的时间戳(以毫秒为单位)
  • 返回 Infinity 表示应在 get 方法中检查软标签

如果你不跟踪标签重新验证时间戳,则返回 0。否则,请在所有提供的标签中查找最近的重新验证时间戳。如果你更愿意在 get 方法中处理软标签检查,则返回 Infinity。

const cacheHandler = {
  async getExpiration(tags) {
    // Return 0 if not tracking tag revalidation
    return 0

    // Or return the most recent revalidation timestamp
    // return Math.max(...tags.map(tag => tagTimestamps.get(tag) || 0));
  },
}

updateTags()

在标签被重新验证或过期时调用。

updateTags(tags: string[], durations?: { expire?: number }): Promise<void>
参数 类型 描述
tags string[] 要更新的标签数组。
durations { expire?: number } 在基于 profile 的重新验证中存在;携带该 profile 的 expire 秒。

你的处理程序应更新其内部状态,将这些标签标记为已失效。

durations 是否存在可告诉你这是哪种失效类型:

  • 不存在:立即失效。携带这些标签的条目不应再被提供。updateTag() 和单参数的 revalidateTag() 走这条路径,且调用方期望其自己的下一次读取会未命中。
  • 存在:标签现在会变陈旧,但携带它们的条目仍可在后台刷新期间继续被提供,直到过了 durations.expire 秒。revalidateTag(tag, 'max') 走这条路径。

返回 Promise<void>。

你的处理器应记录每个标签何时被失效。get() 会将这些时间与条目的 timestamp 进行比较,而 getExpiration() 会对软标签执行相同操作。软标签不会存储在条目的 tags 中,因此删除携带某个标签的条目并不能覆盖revalidatePath()。

const cacheHandler = {
  async updateTags(tags, durations) {
    const now = Date.now()
    for (const tag of tags) {
      const timestamps = tagTimestamps.get(tag) ?? {}
      if (durations) {
        // Serve while refreshing, and expire after `durations.expire` seconds
        timestamps.stale = now
        if (durations.expire !== undefined) {
          timestamps.expired = now + durations.expire * 1000
        }
      } else {
        // Expire immediately
        timestamps.expired = now
      }
      tagTimestamps.set(tag, timestamps)
    }
  },
}

软标签

软标签是 Next.js 基于路由路径自动生成的隐式标签。路径中的每个分段都会获得一个布局标签,此外还有叶子路由本身。例如,路由 /blog/hello 会为 /layout、/blog/layout、/blog/hello/layout 和 /blog/hello 生成软标签。这些标签在内部会加上前缀 _N_T_。

软标签使 revalidatePath() 能够通过同一套基于标签的缓存系统工作。调用 revalidatePath('/blog/hello') 时,它会失效与该路径软标签关联的所有缓存条目。

在缓存处理器 API 中,软标签作为 softTags 参数传递给 get() 方法。你的处理器应检查在缓存条目的 timestamp 之后是否有任何软标签被失效(通过 getExpiration() 或直接比较时间戳)。

如果失效时间比条目更新,请使用 get() 中描述的任一选项将该条目报告为已过期。内置处理器会同时使用两者:对于已过期的标签返回 undefined,对于陈旧的标签返回 revalidate: -1。

分布式标签协调

运行多个 Next.js 实例时,标签失效必须跨实例协调。默认的内存处理器仅在本地跟踪标签,因此在一个实例上调用 revalidateTag() 不会影响其他实例。

要跨实例协调标签:

  1. 调用 revalidateTag() 时,会调用 updateTags()。你的处理器应将失效时间戳写入共享存储。
  2. refreshTags() 在每个请求中运行一次,且在此处理器进行首次读取之前运行。你的处理器应从共享存储中读取最近的失效事件,并更新其本地标签状态。
  3. getExpiration() 返回所有提供的标签中最近的重新验证时间戳。默认实现返回 Math.max(...timestamps, 0)。

以下示例使用 Redis 进行分布式标签协调:

cache-handlers/distributed-tags.jsjs
const { createClient } = require('redis')

const client = createClient({ url: process.env.REDIS_URL })
client.connect()

// Local cache of tag timestamps, synced via refreshTags
const localTagTimestamps = new Map()

module.exports = {
  // ... get() and set() methods ...

  async refreshTags() {
    // Sync tag invalidation timestamps from Redis
    // Using a dedicated set to track tag keys avoids scanning the keyspace
    const tagKeys = await client.sMembers('revalidated-tags')
    if (tagKeys.length > 0) {
      const values = await client.mGet(tagKeys.map((k) => `tag:${k}`))
      for (let i = 0; i < tagKeys.length; i++) {
        localTagTimestamps.set(tagKeys[i], Number(values[i]))
      }
    }
  },

  async getExpiration(tags) {
    const timestamps = tags.map((tag) => localTagTimestamps.get(tag) || 0)
    return Math.max(...timestamps, 0)
  },

  async updateTags(tags, durations) {
    const now = Date.now()
    const pipeline = client.multi()
    for (const tag of tags) {
      pipeline.set(`tag:${tag}`, String(now))
      pipeline.sAdd('revalidated-tags', tag)
      localTagTimestamps.set(tag, now)
    }
    await pipeline.exec()
  },
}

有关标签架构的完整说明(包括软标签和多实例注意事项),请参阅重新验证的工作原理。

错误处理

缓存操作应以防御性方式实现:

  • set() 失败:响应仍会提供给用户,因为 set() 是在响应流已经开始流动之后异步调用的。缓存条目会丢失,下一次请求会触发全新渲染。即便如此,你也应捕获自己的错误:被拒绝的 set() 会加入请求待处理的重新验证工作,在那里它表现为失败的后台任务,而不是渲染错误。
  • get() 失败:你的处理器应捕获内部错误并返回 undefined(“缓存未命中”信号)。框架不会将 get() 包装在 try/catch 中,因此来自 get() 的未处理异常会作为渲染错误传播。
  • 部分写入:如果缓存条目被部分写入后再读取,其行为是未定义的。请使用原子写入或先写入再重命名模式,以避免提供部分条目。

示例

下面的示例展示了处理器如何满足 API 约定。它们省略了生产环境处理器必须添加的淘汰机制、错误处理和多实例协调。cache-handler-redis 示例 是同时实现两个缓存 API 的更完整的 Redis 实现,其 README 还列出了覆盖更多场景的社区处理器。

用于学习和调试的内存处理器

此处理器将条目保存在 Map 中,因此你可以借此记录或检查 Next.js 存储了哪些内容,以及标签如何使其失效。它按进程运行,且没有淘汰机制。内置处理器 同样基于内存,并额外提供了有大小上限的 LRU 和错误处理。

cache-handlers/memory-handler.jsjs
// Entries hold the serialized bytes, never the stream they arrived on
const cache = new Map()
const pendingSets = new Map()
// Tag invalidation times in milliseconds: { stale, expired }
const tagTimestamps = new Map()

function streamFromBytes(bytes) {
  return new ReadableStream({
    start(controller) {
      controller.enqueue(bytes)
      controller.close()
    },
  })
}

module.exports = {
  async get(cacheKey, softTags) {
    // Wait for any pending set operation to complete
    const pendingPromise = pendingSets.get(cacheKey)
    if (pendingPromise) {
      await pendingPromise
    }

    const entry = cache.get(cacheKey)
    if (!entry) {
      return undefined
    }

    // No age check: Next.js compares `timestamp` against `expire` itself.
    // Soft tags are checked by Next.js through `getExpiration()`.
    // This `Map` also has no eviction, which a real handler needs.
    let revalidate = entry.revalidate
    for (const tag of entry.tags) {
      const { stale = 0, expired = 0 } = tagTimestamps.get(tag) ?? {}
      if (expired > entry.timestamp && expired <= Date.now()) {
        return undefined
      }
      if (stale > entry.timestamp) {
        revalidate = -1
      }
    }

    // Every hit gets its own stream over the stored bytes
    return { ...entry, revalidate, value: streamFromBytes(entry.value) }
  },

  async set(cacheKey, pendingEntry) {
    // Create a promise to track this set operation
    let resolvePending
    const pendingPromise = new Promise((resolve) => {
      resolvePending = resolve
    })
    pendingSets.set(cacheKey, pendingPromise)

    try {
      // Wait for the entry to be ready
      const entry = await pendingEntry

      // An in-memory store buffers the stream. Storing the stream itself, or
      // a branch of it, keeps the request that produced the entry alive.
      const value = new Uint8Array(
        await new Response(entry.value).arrayBuffer()
      )

      cache.set(cacheKey, { ...entry, value })
    } finally {
      resolvePending()
      pendingSets.delete(cacheKey)
    }
  },

  async refreshTags() {
    // Tag state lives in this process, so there is nothing to sync
  },

  async getExpiration(tags) {
    return Math.max(
      ...tags.map((tag) => tagTimestamps.get(tag)?.expired ?? 0),
      0
    )
  },

  async updateTags(tags, durations) {
    const now = Date.now()
    for (const tag of tags) {
      const timestamps = tagTimestamps.get(tag) ?? {}
      if (durations) {
        // Serve while refreshing, and expire after `durations.expire` seconds
        timestamps.stale = now
        if (durations.expire !== undefined) {
          timestamps.expired = now + durations.expire * 1000
        }
      } else {
        // Expire immediately
        timestamps.expired = now
      }
      tagTimestamps.set(tag, timestamps)
    }
  },
}

外部存储模式

由 Redis 或数据库支持的处理器必须序列化每个条目。在 set() 中排空流,并在 get() 中根据存储的字节重建流:

cache-handlers/redis-handler.jsjs
const { createClient } = require('redis')

const client = createClient({ url: process.env.REDIS_URL })
client.connect()

module.exports = {
  async get(cacheKey, softTags) {
    // Retrieve from Redis
    const stored = await client.get(cacheKey)
    if (!stored) return undefined

    // Deserialize the entry
    const data = JSON.parse(stored)

    // Reconstruct the ReadableStream from stored data
    return {
      value: new ReadableStream({
        start(controller) {
          controller.enqueue(Buffer.from(data.value, 'base64'))
          controller.close()
        },
      }),
      tags: data.tags,
      stale: data.stale,
      timestamp: data.timestamp,
      expire: data.expire,
      revalidate: data.revalidate,
    }
  },

  async set(cacheKey, pendingEntry) {
    const entry = await pendingEntry

    // Read the stream to get the data
    const reader = entry.value.getReader()
    const chunks = []

    try {
      while (true) {
        const { done, value } = await reader.read()
        if (done) break
        chunks.push(value)
      }
    } finally {
      reader.releaseLock()
    }

    // Combine chunks and serialize for Redis storage
    const data = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)))

    await client.set(
      cacheKey,
      JSON.stringify({
        value: data.toString('base64'),
        tags: entry.tags,
        stale: entry.stale,
        timestamp: entry.timestamp,
        expire: entry.expire,
        revalidate: entry.revalidate,
      }),
      // `EX` needs a positive integer.
      // By definition `expire: Infinity` ("never expire")
      // maps to no TTL at all, so omit `EX` and let Redis persist the key.
      Number.isFinite(entry.expire)
        ? { EX: Math.max(1, Math.ceil(entry.expire)) }
        : {}
    )
  },

  // refreshTags(), getExpiration(), and updateTags() also need shared state.
  // See Distributed Tag Coordination for that half of the handler.
}

平台支持

部署选项 是否支持
Node.js 服务器 是
Docker 容器 是
静态导出 否
适配器 因平台而异

版本历史

版本 变更
v16.0.0 cacheHandlers 已稳定,并从 experimental.cacheHandlers 移至顶层的 cacheHandlers 选项。

相关内容

查看相关 API 参考。

  • use cache:了解如何使用 "use cache" 指令在 Next.js 应用中缓存数据。
  • use cache: remote:了解如何使用 "use cache: remote" 指令,借助远程缓存处理器实现持久化、共享的缓存。
  • use cache: private:了解如何使用 "use cache: private" 指令来缓存访问运行时请求 API 的函数。
  • cacheLife:了解如何在 Next.js 中配置 cacheLife。