Authored by 姜枫

添加页面缓存控制

... ... @@ -94,6 +94,7 @@ try {
const setPageInfo = require('./doraemon/middleware/set-pageinfo');
const devtools = require('./doraemon/middleware/devtools');
const seo = require('./doraemon/middleware/seo');
const pageCache = require('./doraemon/middleware/page-cache');
// YOHO 前置中间件
app.use(subDomain());
... ... @@ -107,16 +108,8 @@ try {
app.use(devtools());
}
// set no cache
app.use((req, res, next) => {
if (req.get('X-Requested-With') === 'XMLHttpRequest') {
res.set('Cache-Control', 'no-cache');
}
next();
});
app.use(pageCache());
require('./dispatch')(app);
app.all('*', errorHanlder.notFound()); // 404
// YOHO 后置中间件
... ...
... ... @@ -13,6 +13,7 @@ var app = express();
var doraemon = path.join(__dirname, '../../doraemon/views'); // parent view root
app.on('mount', function(parent) {
delete parent.locals.settings; // 不继承父 App 的设置
Object.assign(app.locals, parent.locals);
});
... ...
'use strict';
const SECOND = 1;
const MINUTE = 60 * SECOND;
const cachePage = {
'/': 5 * MINUTE,
// 频道页
'/boys': 30 * SECOND,
'/woman': 30 * SECOND,
'/kids': 30 * SECOND,
'/lifestyle': 30 * SECOND,
// 商品详情页
'/product/\/pro_([\d]+)_([\d]+)\/(.*)/': 30 * MINUTE,
// 逛
'/guang': 1 * MINUTE,
'/guang/info/index': 10 * MINUTE,
'/guang/author/index': 1 * MINUTE,
'/guang/tags/index': 1 * MINUTE,
// 领券中心
'/activity/coupon/floor': 5 * MINUTE,
// 商品列表
'/product/list/index': 5 * MINUTE,
'/product/index/index': 5 * MINUTE,
// 秒杀列表
'/product/seckill': 30 * SECOND,
// 秒杀详情
// sale
'/product/sale': 5 * MINUTE,
'/product/outlet': 30 * SECOND,
'/product/index/brand': 2 * MINUTE
};
module.exports = cachePage;
... ...
... ... @@ -73,7 +73,7 @@ module.exports = {
port: 4444 // influxdb port
},
console: {
level: 'info',
level: 'debug',
colorize: 'all',
prettyPrint: true
}
... ...
'use strict';
const path = require('path');
const cachePage = require('../../config/cache');
module.exports = () => {
return (req, res, next) => {
if (req.get('X-Requested-With') === 'XMLHttpRequest') {
res.set('Cache-Control', 'no-cache');
}
function onRender() {
let route = req.route ? req.route.path : '';
let appPath = req.app.mountpath;
let key = path.join(appPath, route.toString()); // route may be a regexp
req.app.set('etag', false);
// 如果存在cache配置,并且业务代码中没有设置
if (cachePage[key] && res.get('Cache-Control') !== 'no-cache') {
res.set({
'Cache-Control': 'max-age=' + cachePage[key]
});
res.removeHeader('Pragma');
res.removeHeader('Expires');
} else {
res.set({
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
Expires: new Date(1900, 0, 1, 0, 0, 0, 0)
});
}
}
res.on('render', onRender);
next();
};
};
... ...
... ... @@ -39,7 +39,7 @@
"request-promise": "^3.0.0",
"serve-favicon": "^2.3.0",
"uuid": "^2.0.3",
"yoho-node-lib": "0.1.23",
"yoho-node-lib": "0.1.25",
"yoho-zookeeper": "^1.0.3"
},
"devDependencies": {
... ...