nuxt3中添加lru-cache缓存页面

2023-01-19

1.在server文件夹中创建middleware文件夹
2.middleware中创建cache.ts
3.npm i lru-cache
4.创建cache
const ssrCache = new LRUCache({
  max: 100,
  maxAge: 1 * 60 * 1000, // 1分钟缓存
});


import LRUCache from "lru-cache";
const ssrCache = new LRUCache({
  max: 100,
  maxAge: 1 * 60 * 1000, // 1分钟缓存
});
// 使用请求的url作为缓存key
function getCacheKey(req: { url: any }) {
  return `${req.url}`;
}

export default defineEventHandler(async (event: any) => {
  const { req, res } = event.node;
  res.original_end = res.end;

if (req.url.includes("/cache-page")) {
    const key = getCacheKey(req);
    const { value } = <any>ssrCache.get(key) || { value: "" };
    if (value) {
      res.setHeader("Cache-Control", "private, max-age=60");
      return res.end(value);
    } else {
      res.end = function (data: any) {
        if (res.statusCode === 200) {
          // 将该页面请求html内容存进LRU
          // 第三个参数缓存时间传undefined则走起初cacheStore定义时的5分钟
          ssrCache.set(key, { value: data }, undefined);
        }

        // html设置客户端缓存60s
        res.setHeader("Cache-Control", "private, max-age=60");
        // 最终返回请求的内容
        return res.original_end(data, "utf-8");
      };
    }
  }
});