nuxt.js服务端缓存lru-cache

对于部分网页进行服务端的缓存,可以获得更好的渲染性能,但是缓存又涉及到一个数据的及时性的问题,所以在及时性和性能之间要有平衡和取舍。

官方文档里面写的使用方法

按照这个配置,试过了没什么用,但是从文档的另外一个地方示例里的代码是能够正常运行的,需要配置的地方有两个:

在使用之前,这个缓存组件并没有默认集成,需要自己安装后才可以使用

npm install lru-cache -s

1.nuxt.config.js

复制代码
module.exports = {
  render: {
    bundleRenderer: {
      cache: require('lru-cache')({
        max: 1000,
        maxAge: 1000 * 60 * 15
      })
    }
  }
}
复制代码

2.vue页面上要配置一个单页的唯一key,通过serverCacheKey()方法返回这个唯一KEY,示例里面用一个时间值,每10秒变化一次来控制缓存的更新频率

复制代码
<template>
  <div>
    <h1>Cached components</h1>
    <p>Look at the source code and see how the timestamp is not reloaded before 10s after refreshing the page.</p>
    <p>Timestamp: {{ date }}</p>
  </div>
</template>

<script>
export default {
  name: 'date',
  serverCacheKey () {
    // Will change every 10 secondes
    return Math.floor(Date.now() / 10000)
  },
  data () {
    return { date: Date.now() }
  }
}
</script>
复制代码

在我按照文档完成这个范例后,刷新网页,其实这个date并没有10秒更新一次,github上已经有人提出这个问题了,按照作者的说法,如果是chrome浏览器可以通过view-source:http://localhost:3000/这个方式去验证,我试了一下的确是10秒更新一次。

我可能需要的是 asyncData() 通过异步获取其他服务器的数据能够被缓存起来,防止每次只要有用户访问网页,但是这个缓存的配置,并不是缓存了所有的信息,每次访问asyncData()还是会执行,然后服务器获取一遍数据....

lru-cache包含的功能可以自己实现这部分的功能,例如每次的get请求缓存

复制代码
import axios from 'axios';
import LRU from 'lru-cache';

const cache = LRU({
  max: 1000,
  maxAge: 1000 * 10,
});

export const get = async (url) => {
  let data = cache.get(url);
  if (data) {
    return JSON.parse(data);
  }
  const res = await axios.get(url);
  data = res.data;
  cache.set(url, JSON.stringify(data));
  return data;
};
复制代码

或者只对lru-cache进行一个简单的包装,在需要使用的地方再使用

复制代码
// 运行与服务端的js
// node.js lru-cache
import LRU from 'lru-cache'

const lruCache = LRU({
  // 缓存队列长度
  max: 2000,
  // 缓存有效期
  maxAge: 60000
})

export const cache = {
  get: function (key) {
    let result = lruCache.get(key)

    if (result) {
      return JSON.parse(result)
    }

    return null
  },
  set: function (key, value) {
    if (value) {
      lruCache.set(key, JSON.stringify(value))

      return true
    }

    return false
  }
}
复制代码

 

posted @   阿弥陀佛呵呵哒  阅读(9918)  评论(1编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示