Commit 6ffdc5d3 authored by Evan You's avatar Evan You

make micro cache controlled via env var

parent 159abf80
...@@ -8,6 +8,7 @@ const resolve = file => path.resolve(__dirname, file) ...@@ -8,6 +8,7 @@ const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-renderer') const { createBundleRenderer } = require('vue-server-renderer')
const isProd = process.env.NODE_ENV === 'production' const isProd = process.env.NODE_ENV === 'production'
const useMicroCache = process.env.MICRO_CACHE !== 'false'
const serverInfo = const serverInfo =
`express/${require('express/package.json').version} ` + `express/${require('express/package.json').version} ` +
`vue-server-renderer/${require('vue-server-renderer/package.json').version}` `vue-server-renderer/${require('vue-server-renderer/package.json').version}`
...@@ -64,16 +65,17 @@ app.use('/manifest.json', serve('./manifest.json', true)) ...@@ -64,16 +65,17 @@ app.use('/manifest.json', serve('./manifest.json', true))
app.use('/service-worker.js', serve('./dist/service-worker.js')) app.use('/service-worker.js', serve('./dist/service-worker.js'))
// 1-second microcache. // 1-second microcache.
const pageCache = LRU({ // https://www.nginx.com/blog/benefits-of-microcaching-nginx/
const microCache = LRU({
max: 100, max: 100,
maxAge: 1000 maxAge: 1000
}) })
// since this app has no user-specific content, every page is cacheable. // since this app has no user-specific content, every page is micro-cacheable.
// if your app involves user-specific content, you need to implement custom // if your app involves user-specific content, you need to implement custom
// logic to determine whether a request is cacheable based on its url and // logic to determine whether a request is cacheable based on its url and
// headers. // headers.
const isCacheable = req => true const isCacheable = req => useMicroCache
app.get('*', (req, res) => { app.get('*', (req, res) => {
if (!renderer) { if (!renderer) {
...@@ -98,7 +100,7 @@ app.get('*', (req, res) => { ...@@ -98,7 +100,7 @@ app.get('*', (req, res) => {
const cacheable = isCacheable(req) const cacheable = isCacheable(req)
if (cacheable) { if (cacheable) {
const hit = pageCache.get(req.url) const hit = microCache.get(req.url)
if (hit) { if (hit) {
if (!isProd) { if (!isProd) {
console.log(`cache hit!`) console.log(`cache hit!`)
...@@ -113,7 +115,7 @@ app.get('*', (req, res) => { ...@@ -113,7 +115,7 @@ app.get('*', (req, res) => {
} }
res.end(html) res.end(html)
if (cacheable) { if (cacheable) {
pageCache.set(req.url, html) microCache.set(req.url, html)
} }
if (!isProd) { if (!isProd) {
console.log(`whole request: ${Date.now() - s}ms`) console.log(`whole request: ${Date.now() - s}ms`)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment