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
  }
}
原文地址:https://www.cnblogs.com/stealth7/p/7372403.html