我为Node.js服务器的速率限制算法提出了一个幼稚的解决方案,我相信有一种方法可以简化它,但是我不确定怎么做。
我们希望将请求限制为每秒50个。因此,如果有最新请求,并且新请求与返回50个请求之间的时间少于一秒钟,则我们应拒绝新请求。
幼稚的实现方式是拥有一个包含50个时间戳的简单数组。每次发生事件时,我们都会为它分配一个Date.now()/ process.hrtime()值。然后,我们查看队列中第50个(最后一个)时间戳的时间戳值和新请求的Date.now()值,如果时间戳的差大于1秒,则我们接受新请求并将其取消移位“队列”,然后从队列中弹出最早的时间戳。但是,如果差异小于1秒,则必须拒绝该请求,并且不将其移到队列中,也不会弹出最早的时间戳。
这是我在Express服务器上的代码
var mostRecentRequestsTimestamps = [];
app.use(function(req,res,next){
if(req.baymaxSource && String(req.baymaxSource).toUpperCase() === 'XRE'){
var now = process.hrtime(); //nanoseconds
if(mostRecentRequestsTimestamps.length < 50){
mostRecentRequestsTimestamps.unshift(now);
next();
}
else{
var lastItem = mostRecentRequestsTimestamps.length -1;
if(now - mostRecentRequestsTimestamps[lastItem] < 1000){ // 1000 milliseconds = 1 second
res.status(503).json({error: 'Server overwhelmed by XRE events'});
}
else{
mostRecentRequestsTimestamps.pop();
mostRecentRequestsTimestamps.unshift(now);
next();
}
}
}
else{
next();
}
});
如您所见,它仅在事件来自某个特定来源的情况下才阻止它们,因此它不应饿死其他类型的请求。此逻辑需要50个时间戳的数据结构,基本上没有任何内容,但我希望有可能的话进一步简化它。有人有想法么?谢谢
这是我最简单的方法:
// oldest request time is at front of the array
var recentRequestTimes = [];
var maxRequests = 50;
var maxRequestsTime = 1000;
app.use(function(req,res,next){
if(req.baymaxSource && String(req.baymaxSource).toUpperCase() === 'XRE'){
var old, now = Date.now();
recentRequestTimes.push(now);
if (recentRequestTimes.length >= maxRequests) {
// get the oldest request time and examine it
old = recentRequestTimes.shift();
if (now - old <= maxRequestsTime) {
// old request was not very long ago, too many coming in during that maxRequestsTime
res.status(503).json({error: 'Exceeded 50 requests per second for XRE events'});
return;
}
}
}
next();
});
这在概念上与您的实现在两个方面不同:
recentRequestTimes
以递增的顺序使用数组(对我的编程大脑而言,这在逻辑上要有意义得多)本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句