Authored by 周少峰

request limit

@@ -14,11 +14,13 @@ const _ = require('lodash'); @@ -14,11 +14,13 @@ const _ = require('lodash');
14 const MAX_TIMES = { 14 const MAX_TIMES = {
15 // 30s 最多访问15次 15 // 30s 最多访问15次
16 30: 15, 16 30: 15,
  17 +
17 // 60s 最多访问15次 18 // 60s 最多访问15次
18 60: 20, 19 60: 20,
  20 +
19 // 100s 最多访问15次 21 // 100s 最多访问15次
20 600: 100 22 600: 100
21 -} 23 +};
22 24
23 module.exports = (limiter, policy) => { 25 module.exports = (limiter, policy) => {
24 const req = limiter.req; 26 const req = limiter.req;
@@ -33,10 +35,9 @@ module.exports = (limiter, policy) => { @@ -33,10 +35,9 @@ module.exports = (limiter, policy) => {
33 35
34 _.forEach(MAX_TIMES, (val, key) => { 36 _.forEach(MAX_TIMES, (val, key) => {
35 ruleKeys.push(`${config.app}:limiter:${key}:max:${limiter.remoteIp}`); // eslint-disable-line 37 ruleKeys.push(`${config.app}:limiter:${key}:max:${limiter.remoteIp}`); // eslint-disable-line
36 - }) 38 + });
37 39
38 return cache.getMultiAsync(ruleKeys).then((results) => { 40 return cache.getMultiAsync(ruleKeys).then((results) => {
39 - console.log(results);  
40 41
41 // 第一次访问 42 // 第一次访问
42 if (_.isEmpty(results)) { 43 if (_.isEmpty(results)) {
@@ -44,7 +45,7 @@ module.exports = (limiter, policy) => { @@ -44,7 +45,7 @@ module.exports = (limiter, policy) => {
44 let cacheTime = val.match(/limiter:([^:]*)?:max/i)[1]; 45 let cacheTime = val.match(/limiter:([^:]*)?:max/i)[1];
45 46
46 cache.setAsync(val, 1, +cacheTime); // eslint-disable-line 47 cache.setAsync(val, 1, +cacheTime); // eslint-disable-line
47 - }) 48 + });
48 49
49 return Promise.resolve(true); 50 return Promise.resolve(true);
50 } 51 }
@@ -63,9 +64,11 @@ module.exports = (limiter, policy) => { @@ -63,9 +64,11 @@ module.exports = (limiter, policy) => {
63 if (!req.xhr) { 64 if (!req.xhr) {
64 cache.incrAsync(val, 1); 65 cache.incrAsync(val, 1);
65 } 66 }
66 - }) 67 + });
67 68
68 // 不满足任何限制规则,继续访问 69 // 不满足任何限制规则,继续访问
69 return Promise.resolve(true); 70 return Promise.resolve(true);
70 - }).catch(err=>{logger.error(err)}); 71 + }).catch(err=>{
  72 + logger.error(err);
  73 + });
71 }; 74 };