我正在使用 pm2(集群模式)和 redis。我想要路由级速率限制配置。 docs 提到,如果我们在多个服务器上设置了 fastify-rate-limit,则必须设置 redis 属性,我假设这适用于我,因为我正在使用 pm2。
这是我的 fastify 配置:
const createClient = require('redis').createClient;
fastify.register(require('@fastify/rate-limit'), {
global : false,
redis: createClient("redis://redis_url")
})
我正在测试速率限制的示例路线。
fastify.get('/hello',{
config: {
rateLimit: {
max: 1,
timeWindow: '1 minute'
}
}
}, async (req, reply) => {
reply.send("world")
})
但是,它不起作用。我每分钟可以多次到达
/hello
路线。
我该如何解决这个问题?
这里是同样的问题
您需要
await
插件才能使其正常工作。
await fastify.register(require('@fastify/rate-limit'), {
global : false,
redis: createClient("redis://redis_url")
})
fastify.get('/hello', { ... })
这是需要的,因为
onRoute
钩子,它是 fastify@4
重大变化的一部分:https://www.fastify.io/docs/latest/Guides/Migration-Guide-V4/#synchronous-route-definitions -2954