【发布时间】:2021-07-10 00:04:44
【问题描述】:
我的应用服务器为每个租户使用一个数据库,我需要一次连接到多个数据库。为了使用 Sequelize 做到这一点,我维护了一个数据库池,我在其中添加了到 Map 的连接:
addConnection(dbKey) {
const sequelize = new Sequelize(
dbKey,
"username",
"password",
{
host: localhost,
port: 5000,
schema: 'main',
dialect: 'postgres'
}
);
const models = {
sequelize: sequelize,
customerData: CustomerData(sequelize, DataTypes)
}
this.dbPool.set(dbKey, models);
}
这使我可以根据需要检索续集实例。目前,我没有看到对管理与多个数据库的连接的单个 sequelize 实例的任何支持。而且因为我正在维护自己的连接图,所以我似乎需要执行释放空闲连接的任务。
如果在一定时间间隔内未使用空闲连接,我想关闭它们并将它们从 Map 中删除。我考虑了几种方法,但不知道哪种方法可行。它真的归结为 2..
1 - 为 Sequelize 实例设置 options.pool.idle。
> The maximum time, in milliseconds, that a connection can be idle before being released.
AFAIK 这不符合我的要求,它只会在同一数据库存在连接池时设置超时,所以这显然行不通。
2 - 使用 SetInterval 关闭连接并在空闲时从 Map 对象中删除它们的引用。
a) When opening connection, set a timestamp along with connection.
b) Whenever the sequelize instance is used to make a query, update the timestamp.
c) Every minute or so, close and free any connections that have been idle for longer than some time period.
如果 Sequelize 或 getter 中有一些内部字段可以让我看到上次使用连接的时间,那就太好了。查看 Sequelize 和模型实例的 API,我没有看到这样的字段或方法。有没有办法确定 Sequelize 库中上次使用连接的时间?
【问题讨论】:
标签: node.js sequelize.js