Authored by 周少峰

Merge branch 'hotfix/limit'

... ... @@ -15,7 +15,7 @@ const cachePage = {
'/lifestyle/': 30 * SECOND,
// 商品详情页
'/product/\\/([\\d]+)(.*)/': 5 * MINUTE,
'/product/^\\/([\\d]+)(.*)/': 5 * MINUTE,
// 逛
'/guang/': 1 * MINUTE,
... ...
... ... @@ -30,7 +30,9 @@ module.exports = (limiter, policy) => {
next = limiter.next; // eslint-disable-line
const key = `pc:limiter:${limiter.remoteIp}`;
const keyMax = `pc:limiter:max:${limiter.remoteIp}`;
const key10m = `pc:limiter:10m:${limiter.remoteIp}`;
const key10mMax = `pc:limiter:10m:max:${limiter.remoteIp}`;
res.on('render', function() {
let route = req.route ? req.route.path : '';
... ... @@ -49,13 +51,18 @@ module.exports = (limiter, policy) => {
}
});
return cache.getMultiAsync([key, key10m]).then((results) => {
return cache.getMultiAsync([key, key10m, keyMax, key10mMax]).then((results) => {
let result = results[key];
let result10m = results[key10m];
logger.debug('qps limiter: ' + key + '@' + result + ' max: ' + MAX_QPS);
logger.debug('qps limiter:10m ' + key10m + '@' + result10m + ' max: ' + MAX_QPS_10m); // eslint-disable-line
// 达到1分钟或是10分钟的访问限制,禁止访问
if (results[keyMax] === 1 || results[key10mMax] === 1) {
return Promise.resolve(policy);
}
// 默认数据设置
if (!result && !_.isNumber(result)) {
cache.setAsync(key, 1, 60); // 设置key,1m失效
... ... @@ -79,7 +86,7 @@ module.exports = (limiter, policy) => {
res.statusCode = 403;
return Promise.resolve(policy);
} else if (result10m > MAX_QPS_10m) { // eslint-disable-line
cache.touch(key10m, ONE_DAY);
cache.setAsync(key10mMax, 1, ONE_DAY);
logger.debug('req limit', key10m);
return Promise.resolve(policy);
... ... @@ -90,7 +97,7 @@ module.exports = (limiter, policy) => {
res.statusCode = 403;
return Promise.resolve(policy);
} else if (result > MAX_QPS) { // 判断 qps
cache.touch(key, ONE_DAY);
cache.setAsync(keyMax, 1, ONE_DAY);
logger.debug('req limit', key);
return Promise.resolve(policy);
... ...