nuxt.js 缓存实践

2020-06-14 06:03:23易采站长站整理

api的请求使用 axios , axios 即可以在服务端使用也可是在浏览器使用,代码大概长这样子


import axios from 'axios'
import md5 from 'md5'
import LRU from 'lru-cache'

// 给api加3秒缓存
const CACHED = LRU({
max: 1000,
maxAge: 1000 * 3
})

function request (config) {
let key
// 服务端才加缓存,浏览器端就不管了
if (config.cache && !process.browser) {
const { params = {}, data = {} } = config
key = md5(config.url + JSON.stringify(params) + JSON.stringify(data))
if (CACHED.has(key)) {
// 缓存命中
return Promise.resolve(CACHED.get(key))
}
}
return axios(config)
.then(rsp => {
if (config.cache && !process.browser) {
// 返回结果前先设置缓存
CACHED.set(key, rsp.data)
}
return rsp.data
})
}

使用上跟平时使用 axios 还是一样的,就多加了个 cache 的属性标识是否需要在服务端做缓存


const api = {
getGames: params => request({
url: '/gameInfo/gatGames',
params,
cache: true
})
}

页面级别的缓存

在不依赖于登录态以及过多参数的情况下,如果并发量很大,可以考虑使用页面级别的缓存, 在

 nuxt.config.js 
增加
serverMiddleware 
属性


const nuxtPageCache = require('nuxt-page-cache')

module.exports = {
serverMiddleware: [
nuxtPageCache.cacheSeconds(1, req => {
if (req.query && req.query.pageType) {
return req.query.pageType
}
return false
})
]}

上面的例子根据链接后面的参数 pageType 去做缓存,如果链接后面有 pageType 参数,就做缓存,缓存时间为1秒,也就是说在1秒内相同的 pageType 请求,服务端只会执行一次完整的渲染

nuxt-page-cache 参考了route-cache ,写得比较简陋,你也可以重新封装下,nuxt最终返回数据是使用 res.end(html, ‘utf-8’) ,页面级别的缓存大概的思想如下:


const LRU = require('lru-cache')

let cacheStore = new LRU({
max: 100, // 设置最大的缓存个数
maxAge: 200
})

module.exports.cacheSeconds = function (secondsTTL, cacheKey) {
// 设置缓存的时间
const ttl = secondsTTL * 1000
return function (req, res, next) {
// 获取缓存的key值
let key = req.originalUrl
if (typeof cacheKey === 'function') {
key = cacheKey(req, res)
if (!key) { return next() }
} else if (typeof cacheKey === 'string') {