NodeJS rate-limiter-flexible giving me an error Lua redis()命令参数必须是字符串或整数\

kcugc4gi  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(140)

我正在使用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'

bvpmtnay

bvpmtnay1#

简短回答:使用legacyMode: true选项创建Redis客户端。

const redisClient = redis.createClient({
  legacyMode: true,
  host: 'localhost',
  port: 6379
})

产品名称:node-redis版本4包有突破性的变化,你可以阅读他们hererate-limiter-flexible不支持新的node-redis包API,所以你应该使用legacyMode: true。或者,您可以使用ioredis包。或者贡献给rate-limiter-flexible以支持node-redis v4+ API。

相关问题