Authored by 陈峰

解决lru内存占用过大问题

... ... @@ -2,6 +2,7 @@ const fs = require('fs');
const path = require('path');
const rp = require('request-promise');
const LRU = require('lru-cache');
const url = require('url');
const _ = require('lodash');
const pkg = require('../../package.json');
const logger = global.yoho.logger;
... ... @@ -15,22 +16,27 @@ const routes = [
},
{
route: '/channel',
cacheRule: 'pathname',
cache: true
},
{
route: '/channel/search',
cacheRule: 'pathname',
cache: true
},
{
route: '/channel/men',
cacheRule: 'pathname',
cache: true
},
{
route: '/channel/women',
cacheRule: 'pathname',
cache: true
},
{
route: '/about',
cacheRule: 'pathname',
cache: true
},
];
... ... @@ -40,7 +46,7 @@ let renderer;
let template = fs.readFileSync(path.join(__dirname, '../../src/index.html'), 'utf-8');
const microCache = LRU({ // eslint-disable-line
max: 10000,
max: 1000,
maxAge: 2000
});
... ... @@ -60,10 +66,12 @@ const getContext = (req) => {
};
};
const render = (options) => {
const render = ({cache, cacheRule}) => {
return (req, res, next) => {
if (options.cache) {
const html = microCache.get(req.url);
const reqUrl = url.parse(req.url);
if (cache && reqUrl[cacheRule]) {
const html = microCache.get(reqUrl[cacheRule]);
if (html) {
console.log('cache', req.url);
... ... @@ -77,8 +85,8 @@ const render = (options) => {
// TODO 处理错误类型
return next(err);
}
if (options.cache) {
microCache.set(req.url, html);
if (cache && reqUrl[cacheRule]) {
microCache.set(reqUrl[cacheRule], html);
}
return res.send(html);
});
... ... @@ -154,9 +162,7 @@ module.exports = async (app) => {
await loadBundle();
_.each(routes, r => {
if (!r.disable) {
app.get(r.route, ssrRender({
cache: r.cache
}));
app.get(r.route, ssrRender(r));
}
});
};
... ...