我尝试在 nextjs 后端使用“节点缓存”,但似乎不起作用。 这是我的缓存文件
缓存.ts
import NodeCache from 'node-cache';
const Cache = new NodeCache({ stdTTL: 60 * 60 * 6 }); // 6 hours
export default Cache;
当请求命中 API1 时,我会进行一些计算并将结果保存在节点缓存中
API1
import Cache from '@/utils/cache';
async function fetchFromUrl(url: string): Promise<UrlContent | null> {
try {
const cachedContent = Cache.get<UrlContent>(url);
if (cachedContent) {
return cachedContent;
}
....
Cache.set(url, cleanedContent);
console.log(url, Cache.keys(), Cache.get(url)); // i can get results here
return cleanedContent;
}
但是当另一个请求命中 API2 时,我无法从缓存中获取数据。
API2
import Cache from '@/utils/cache';
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method !== 'POST') {
// Handle any methods other than POST
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
} else {
// Extract urls from the request body
const { urls, question } = req.body as UrlRequestBody;
if (!urls || !Array.isArray(urls) || urls.length === 0 || !question) {
return res.status(400).json({ message: 'Invalid request body' });
}
console.log(
urls[0] as string,
question,
Cache.keys(), // no key returned
Cache.get(urls[0] as string) // can't get the results
);
抱歉耽搁了,但我刚刚在尝试解决同样的问题时遇到了这个线程。
我不确定这是否是最好的解决方案,但我希望它对某人有帮助。
我所做的是将 NodeCache 存储在全局变量中,如下所示:
import NodeCache from 'node-cache';
if (!global.cacheInstance) {
global.cacheInstance = new NodeCache({ stdTTL: 60, checkperiod: 60 });
}
const cache = global.cacheInstance;
export default cache;
通过这样做,实例化它不再生成新的 NodeCache 对象,确保 API 之间存在一定的数据持久性。
import cache from "@/lib/cache";
export async function GET(request) {
console.log(cache.get("example"));
return Response.json({ m: 'Hello from Next.js!' });
}