在Next.js中使用Cachified时如何删除缓存值?
问题解决:Next.js中cachified + lru-cache无法跨上下文删除缓存
核心原因
你的问题本质是Next.js的不同服务上下文(getServerSideProps和API路由)运行在独立的Node.js进程中,导致你创建的lruCache实例是进程隔离的:
- 在
getServerSideProps中调用cachedUserByName时,缓存数据存在页面服务进程的LRU实例里 - 调用API路由的
clearCache时,操作的是API服务进程的另一个LRU实例,自然找不到对应的缓存key - 而
file-system-cache基于文件存储,跨进程共享,所以功能正常
解决方案
方案1:改用跨进程共享的缓存(生产环境推荐)
内存缓存无法跨进程/服务器共享,生产环境建议用Redis这类分布式缓存。示例代码如下:
import { cachified } from 'cachified'; import Redis from 'ioredis'; import { redisCacheAdapter } from '@epic-web/cachified-redis'; // 初始化Redis客户端 const redis = new Redis({ host: process.env.REDIS_HOST, port: parseInt(process.env.REDIS_PORT || '6379'), }); const cache = redisCacheAdapter(redis); export const cachedUserByName = (name: string): Promise<any> => { const cacheId = `user-${name}`; return cachified<any>({ key: cacheId, cache, async getFreshValue() { const { firstName, lastName } = await getInformation(name); return { information: { firstName, lastName }, }; }, ttl: 10 * 1000, staleWhileRevalidate: Infinity, }); }; export function clearCache(key: string) { return redis.del(key); }
方案2:强制单进程运行(仅开发调试用)
在开发模式下,你可以让Next.js的页面服务和API路由共享同一个进程,修改package.json的启动脚本:
{ "scripts": { "dev": "next dev --no-lazy" } }
注意:此方法仅适合开发调试,生产环境多进程部署时依然会失效。
方案3:使用Next.js官方缓存API(App Router)
如果你用Next.js 13+的App Router,可以用unstable_cache替代cachified,它会自动处理Next.js的上下文缓存:
import { unstable_cache } from 'next/cache'; const getCachedUser = unstable_cache( async (name: string) => { const { firstName, lastName } = await getInformation(name); return { information: { firstName, lastName } }; }, ['user'], // 缓存键前缀 { revalidate: 10 } // TTL(秒) ); export const cachedUserByName = (name: string) => getCachedUser(name); // 清除缓存(需要用revalidateTag) export function clearCache(name: string) { revalidateTag(`user-${name}`); }
其他内存缓存机制推荐
Map/WeakMap:Node.js内置,适合简单的键值缓存,无LRU淘汰,适合小规模缓存场景。quick-lru:轻量级LRU缓存库,体积远小于lru-cache,API简洁。memory-cache:支持TTL的简单内存缓存,API类似Redis,适合快速实现缓存逻辑。node-cache:功能丰富的内存缓存,支持TTL、缓存命中统计,适合需要更多监控的场景。
内容的提问来源于stack exchange,提问作者Or Nakash
相关产品推荐
相关产品推荐

