jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

vue2.xx ssr node 服务器端缓存请求 #8

Open jackieli123723 opened 7 years ago

jackieli123723 commented 7 years ago

1. 安装缓存依赖: lru-cache

npm install lru-cache --dev

2. api 配置文件

config-server.js

var LRU = require('lru-cache')

let api
if (process.__API__) {
api = process.__API__
} else {
api = process.__API__ = {
api: 'http://localhost:8080/api/',
cached: LRU({
max: 1000,
maxAge: 1000 * 60 * 15
}),
cachedItem: {}
}
}

module.exports = api

配置下lru-cache

3. 封装下 api

import axios from 'axios'
import qs from 'qs'
import md5 from 'md5'
import config from './config-server.js'

export default {
post(url, data) {
const key = md5(url + JSON.stringify(data))
if (config.cached && config.cached.has(key)) {
return Promise.resolve(config.cached.get(key))
}
return axios({
method: 'post',
url: config.api + url,
data: qs.stringify(data),
// 其他配置
}).then(res => {
if (config.cached && data.cache) config.cached.set(key, res)
return res
})
}
}

ajax 库我们用axios, 因为axios在 nodejs 和 浏览器都可以使用 并且将 node 端和浏览器端分开封装

import config from './config-server.js'
const key = md5(url + JSON.stringify(data))

通过 url 和参数, 生成一个唯一的 key

if (config.cached && config.cached.has(key)) {
return Promise.resolve(config.cached.get(key))
}
if (config.cached && data.cache) config.cached.set(key, res)

判断下是不是开启了缓存, 并且接口指定缓存的话, 将 api 返回的数据, 写入缓存

注意: 这个 api 会处理所有的请求, 但是很多请求其实是不需要缓存的, 所以需要缓存可以在传过来的 data 里, 添加个 cache: true, 如:

api.post('/api/test', {a: 1, b:2, cache: true})

不需要缓存的直接按正常传值即可 当然这里标记是不是要缓存的方法有很多, 不一定要用这一种