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
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM