我正在尝试通过 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.
你的问题是
client = await pool.acquire()
then
块或类似的东西中构建逻辑,但让主线程继续运行并更快地控制连接切换,例如在取回值并释放池后完成进程需要执行的任何操作,因此,当它可以再次获取它时,它就准备好继续工作并接受下一个命令。