@H_404_0@vue缓存分为页面缓存、组建缓存、接口缓存,这里我主要说到了页面缓存和组建缓存
@H_404_0@
页面缓存:
@H_404_0@在server.js中设置
<div class="jb51code">
<pre class="brush:js;">
const LRU = require('lru-cache')
const microCache = LRU({
max: 100,// 最大缓存的数目
maxAge: 1000 // 重要提示:条目在 1 秒后过期。
})
const isCacheable = req => {
//判断是否需要页面缓存
if (req.url && req.url === '/') {
return req.url
} else {
return false
}
}
app.get('*',(req,res) => {
const cacheable = isCacheable(req)
if (cacheable) {
const hit = microCache.get(req.url)
if (hit) {
return res.end(hit)
}
}
const errorHandler = err => {
if (err && err.code === 404) {
// 未找到页面
res.status(404).sendfile('public/404.html');
} else {
// 页面渲染错误
res.status(500).end('500 - Internal Server Error')
console.error(error during render : ${req.url}
)
console.error(err)
}
}
const context = {
title: 'vue',keywords: 'vue-ssr服务端脚手架',description: 'vue-ssr-template,vue-server-renderer',version: v,url: req.url,cookies: req.cookies
}
renderer.renderToString(context,(err,html) => {
if (err) {
return errorHandler(err)
}
res.end(html)
microCache.set(req.url,html) // 设置当前缓存页面的内容
})
})