express-rate-limit库将在每个时间单位超过一定数量的请求后阻止来自客户端的连接(假设由IP标识)。它还会在相当于时间单位的时间内阻止连接。
因此,如果它被设置为在每分钟120个请求后阻止连接;它还会阻止IP一分钟。如何延长阻塞时间?
下面是我当前的示例:
...
var express = require('express');
var app = express();
const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
limiter = new RateLimit({
store: new RedisStore({
expiry: 60
}),
max: 120
});
app.use(limiter);
...在这里,我也使用了rate-limit-redis,它的expiry参数覆盖了express-rate-limit的windowMs参数。
发布于 2020-05-03 00:49:35
通过onLimitReached回调,您可以记录该IP再次解封的时间。然后,您可以编写另一个中间件来检查何时到达解锁日期。
在下面的示例中,bannedIPs保存IP再次解封的时间记录,banner是根据当前日期使用该时间对IP进行封堵的中间件。
...
var express = require('express');
var app = express();
const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
// Keep the IPs that are banned
const bannedIPs = {};
limiter = new RateLimit({
store: new RedisStore({
expiry: 60
}),
onLimitReached: function(req, res, options) {
// The IP will be unblocked again in an hour (60*60*1000)
bannedIPs[req.ip] = +new Date() + 60*60*1000;
},
max: 120
});
banner = function(req, res, next) {
// If the current Date is still before than the unblocking date,
// send a 429 message indicating too many requests
if (bannedIPs[req.ip] >= +new Date()) {
res.status(429).send("Sorry, too many requests: " + new Date(bannedIPs[req.ip]));
} else {
next();
}
}
app.use(banner);
app.use(limiter);
...有很多改进的空间,例如,一旦is不再被阻止,就将其移除,并可能将密钥存储在Redis中,以便在重启服务器后保持持久。但是,这将给你一个起点。
https://stackoverflow.com/questions/61563026
复制相似问题