Vue SSR服务端渲染之数据缓存

当我们在做vue的服务器端渲染时,可能会碰到各种各样的坑,内存泄露就是其中的一种。当然,导致内存泄露的原因有很多,不合理使用Axios也是其中一种,那下面我给大家介绍一下如何有效的避免请求中的内存泄露。

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:8181/api/',
        //配置缓存
        cached: LRU({
            max: 1000,
            maxAge: 1000 * 60 * 15
        }),
        cachedItem: {}
    }
}

module.exports = api

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

不需要缓存的直接按正常传值即可

猜你喜欢

转载自blog.csdn.net/itKingOne/article/details/81136589