我正在尝试使用连接池来管理 Node.js 应用程序中的 Redis 连接,但遇到了以下问题:超出了连接到数据库的客户端,并且正在创建新的客户端连接,即使连接在之后释放返回响应。 我正在使用 netlify 函数和 redis 云免费层,它只有 30 个连接。
这是我用来创建连接池的代码:
const Redis = require('ioredis-rejson');
const { createPool } = require('generic-pool');
const pool = createPool({
create: () => new Redis({
port:xx,
host : "xx",
password :"xx",
username: "",
keyPrefix: 'myapp:'
}),
destroy: client => client.disconnect(),
max: 10, // maximum number of connections to create at once
min: 2, // minimum number of connections to keep in the pool
idleTimeoutMillis: 30000, // how long a connection can be idle before being released
acquireTimeoutMillis: 5000, // how long to wait for a connection to become available
});
exports.handler = async (event, context, callback) => {
console.log(`Acquiring connection from pool (size=${pool.size}, available=${pool.available})`);
let client;
try {
// acquire a connection from the pool
client = await pool.acquire();
console.log(`Acquired connection: ${client.address}`);
const cachedResult = await client.json_get('results');
console.log(`Retrieved connection: ${client.address}`);
return {
statusCode: 200,
body: JSON.stringify(cachedResult),
};
} catch (error) {
console.error(error);
return {
statusCode: 500,
body: JSON.stringify('Something went wrong'),
};
} finally {
// always release the connection back to the pool
if (client) {
pool.release(client);
console.log(`Released connection: ${client.address}`);
}
}
};
此外,由于某种原因,控制台登录时 client.address 为
undefined
,并且为 pool (size=0, available=0)
。
我之前遇到过 Redis 挂在断开的连接上并导致连接过多的问题。不确定它是服务器设置还是什么,但我已经看到它有多种语言版本。
无论如何,出于这个原因,我总是调用
.quit
来代替——尽管它很快就会被弃用。 QUIT 命令实际上由 Redis 接收并处理,然后 Redis 结束连接。
我没有使用单独的包来管理连接池,而是选择在整个项目中将 Redis 初始化为单例。通过这样做,我根据需要调整了isolationPoolOptions来控制连接池行为。
import { createClient } from 'redis';
const redisClient = createClient({
url: <url>,
isolationPoolOptions: {
min: 1,
max: 30
})
}