我严格的利率限制是不正常的。我想在60秒内允许20次点击,如果你的用户超过了这个限制,那么它们应该会被阻止60秒。
这是我的代码->
要使用
,您需要做“npm安装优化-速率限制”。
fastify.register(require('fastify-rate-limit'),
{
keyGenerator (req) {
let requestUrl = req.raw.url;
requestUrl = requestUrl.split('/');
let apiName = requestUrl[requestUrl.length - 1].replace('/','');
return req.raw.ip+apiName;
},
max: 20,
timeWindow: 1000*60,
addHeaders: {
'x-ratelimit-limit': true,
'x-ratelimit-remaining': true,
'x-ratelimit-reset': true,
'retry-after': true
},
});
我想实现->的场景
用户A在32秒内请求了一个API 20次,这意味着他现在已经用尽了他的命中配额(因为他只能在60秒内完成20次命中),如果现在他在剩下的28秒内提出另一个请求,那么他将被阻止请求该API 60秒。
发布于 2021-07-15 02:45:51
如果不实现自己的customStorage
,就无法对其进行归档。默认内存实现有一个时钟,当timeWindow
离开时会打开它。所以你每60秒就能得到20次回复。它不会在达到极限后60秒开始计数。
此外,我还将keyGenerator
升级到:
return `${req.raw.ip}-${req.routerPath}`
因为这个函数可以被http://localhost/api?a=1
、http://localhost/api?a=2
等欺骗。因为原始URL正在变异
https://stackoverflow.com/questions/68389417
复制相似问题