You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为@fastify/caching按路由配置?设置max-age或禁用特定路由缓存

fastify-caching按路由配置缓存的解决方案

核心结论

fastify-caching支持按路由单独配置缓存规则,包括设置专属max-age(对应expiresIn)或完全禁用特定路由缓存,无需受全局配置限制。


1. 按路由单独设置缓存有效期(max-age)

在路由定义的config字段中添加caching配置,即可覆盖全局的expiresIn参数,实现单路由专属缓存时长:

// 全局缓存配置(默认300秒)
fastify.register(require('fastify-caching'), {
  privacy: 'public',
  expiresIn: 300,
  // 其他全局缓存配置...
})

// 单独配置缓存有效期的路由
fastify.get('/user-profile', {
  config: {
    caching: {
      expiresIn: 600, // 该路由缓存有效期设为10分钟(600秒),覆盖全局配置
      privacy: 'public'
    }
  },
  handler: async (req, reply) => {
    return { userId: 123, name: 'John Doe' }
  }
})

2. 完全禁用特定路由的缓存

有两种简洁的实现方式:

方式1:通过路由config直接禁用

在路由的config中设置caching: false,即可跳过该路由的所有缓存逻辑:

fastify.get('/real-time-data', {
  config: {
    caching: false // 完全禁用该路由的缓存
  },
  handler: async (req, reply) => {
    // 返回实时生成的数据
    return { timestamp: Date.now(), data: '实时更新内容' }
  }
})

方式2:通过响应头控制

手动设置HTTP缓存头,强制客户端和中间件不缓存该路由的响应:

fastify.get('/no-cache-api', async (req, reply) => {
  reply.header('Cache-Control', 'no-store, no-cache, must-revalidate')
  reply.header('Pragma', 'no-cache')
  reply.header('Expires', '0')
  return { data: '该响应不会被缓存' }
})

补充说明

全局配置中的expiresIn仅作为默认值生效,当路由存在单独的caching配置时,路由级配置优先级更高。

内容的提问来源于stack exchange,提问作者TheWoozyDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:10:21