我正在使用rate-limiter-flexible应用费率限制
const redis = require('redis');
const { RateLimiterRedis } = require('rate-limiter-flexible');
这是我的密码
/ Create a Redis client
const redisClient = redis.createClient({
host: 'localhost', // Replace with your Redis server hostname
port: 6379 // Replace with your Redis server port
});
// Define rate limiting options
const rateLimitOptions = {
storeClient: redisClient,
keyPrefix: 'rate-limiter:',
points: 10, // Number of points a user can accumulate before getting rate limited
duration: 60, // Time window in seconds
blockDuration: 60 // Time in seconds for which a user will be blocked after getting rate limited
};
// Create a rate limiter instance
const rateLimiter = new RateLimiterRedis(rateLimitOptions);
// Express middleware to enforce rate limiting
const rateLimitMiddleware = async (req, res, next) => {
const ip = req.connection.remoteAddress; // Get the user's IP address
const url = req.originalUrl; // Get the URL of the request
const key = `${url}_${ip}`;// Use a combination of IP and URL as the key
try {
const rateLimiterRes = await rateLimiter.consume(key); // Pass the key and points as arguments
next(); // Call next() to proceed to the next middleware or route handler
} catch (rejRes) {
// Handle rate limit exceeded
const remainingTime = Math.ceil(rejRes.msBeforeNext / 1000);
它在这一行给我错误Lua redis()命令参数必须是字符串或整数\
const rateLimiterRes = await rateLimiter.consume(key); // Pass the key and points as arguments
我传递的密钥是'/v2.0/json/login-user_::1'
1条答案
按热度按时间bvpmtnay1#
简短回答:使用
legacyMode: true
选项创建Redis客户端。产品名称:
node-redis
版本4包有突破性的变化,你可以阅读他们here。rate-limiter-flexible
不支持新的node-redis
包API,所以你应该使用legacyMode: true
。或者,您可以使用ioredis
包。或者贡献给rate-limiter-flexible
以支持node-redis
v4+ API。