我正在使用net.Server作为我的TCP服务器。
如何执行消息速率限制?
我发现了Express(express-rate-limit)和Websocket(websocket-rate-limit)的类似解决方案,但TCP却没有。
rate-limiter-flexible包可用于此目的。
它支持Redis,MongoDB等许多存储。这是内存存储中最简单的示例:
const opts = {
points: 10, // 10 points
duration: 1, // Per second
};
const rateLimiter = new RateLimiterMemory(opts);
rateLimiter.consume(remoteAddress, 1) // consume 1 point
.then((rateLimiterRes) => {
// 1 point consumed
// Some app logic here
})
.catch((rateLimiterRes) => {
// Not enough points to consume
});