通用池最大和最小不工作

问题描述 投票:0回答:1

我正在尝试通过 Node.js 服务器访问 Redis 并通过 API 发送数据。为了减轻服务器的压力,因为这将被多次调用,我将连接池与

generic-pool
库一起使用。我已经配置了所有内容,并且它正在工作,但连接池未按预期运行。当我将最大值设置为 20 并异步发送 30 个请求时,所有请求仍处于待处理状态。我不确定出了什么问题。

相关代码如下:

var PASSWORD = config.REDIS_PASSWORD;
var pool = createPool({
  create: () => {
    console.log("Creating new Redis client...");
    return new Promise((resolve, reject) => {
      const client = PASSWORD
        ? redis.createClient({
            host: config.REDIS_HOST,
            port: config.REDIS_PORT,
            password: PASSWORD,
          })
        : redis.createClient({
            host: config.REDIS_HOST,
            port: config.REDIS_PORT,
          });

      client.on("error", (err) => {
        console.error("Redis error:", err);
        reject(err);
      });

      client.on("ready", () => {
        console.log("Redis client ready");
        resolve(client);
      });
    });
  },
  destroy: (client) => {
    console.log("Destroying Redis client...");
    return new Promise((resolve) => {
      client.quit(() => {
        console.log("Redis client destroyed");
        resolve();
      });
    });
  },
  max: 20,
  min: 3,
});

const logPoolStats = () => {
  console.log(`Pool Size: ${pool.size}`);
  console.log(`Available: ${pool.available}`);
  console.log(`Borrowed: ${pool.borrowed}`);
  console.log(`Pending: ${pool.pending}` + "\n");
};

app.post("/executeCommand", async (req, res) => {
  const { redisKey, command, args = [] } = req.body;

  if (!redisKey || !command) {
    console.log("Invalid parameters received:", req.body);
    return res.status(400).json({ error: "Invalid parameters" });
  }

  let argumentsArray = Array.isArray(args) ? args : JSON.parse(args);
  argumentsArray = [redisKey, ...argumentsArray];

  let client;
  try {
    logPoolStats();
    client = await pool.acquire();
    logPoolStats();
    if (typeof client[command] === "function") {
      client[command](...argumentsArray, (err, result) => {
        pool.release(client);
        console.log("Client released back to pool");
        logPoolStats();
        if (err) {
          console.error(`Error executing command ${command}:`, err);
          return res
            .status(500)
            .json({ error: "Failed to execute Redis command" });
        }
        console.log(`Executed command ${command} with result:`);
        return res.json({
          command: command,
          data: result,
        });
      });
    } else {
      console.log(`Invalid Redis command attempted: ${command}`);
      pool.release(client);
      return res
        .status(400)
        .json({ error: `Invalid Redis command: ${command}` });
    }
  } catch (error) {
    if (client) {
      pool.release(client);
    }
    console.error("Failed to execute Redis command:", error);
    return res.status(500).json({ error: "Failed to execute Redis command" });
  }
});```


I attempted to increase the maximum value for the connection pool, but even after doing so, the requests are still not being processed as expected. When I send asynchronous requests beyond the maximum limit, they remain in a pending state rather than being executed. This issue persists regardless of how I adjust the pool settings. I'm unsure about the underlying problem and would appreciate any insights or suggestions.
node.js npm connection-pooling
1个回答
0
投票

你的问题是

client = await pool.acquire()

您将await 放在promise 上,这样主线程就会被阻塞,直到您获得池为止,这意味着一次只有一个连接在工作。
让它成为一个承诺,并在
then
块或类似的东西中构建逻辑,但让主线程继续运行并更快地控制连接切换,例如在取回值并释放池后完成进程需要执行的任何操作,因此,当它可以再次获取它时,它就准备好继续工作并接受下一个命令。
您构建它的方式是连接池的同步使用。

© www.soinside.com 2019 - 2024. All rights reserved.