Should I keep Sequelize instance throughout server running time?

Ovi*_*lia 3 node.js sequelize.js

I have a Sequelize instance and it is exported in a file to be accessed when doing DB operations.

const sequelize = new Sequelize('database', 'username', null, {
  dialect: 'mysql'
});
module.exports = sequelize;
Run Code Online (Sandbox Code Playgroud)

So the instance is created when the expressjs server starts and never destroys. I wonder if this is the correct way to do, or should I call new Sequelize every time I use the DB operation?

I think it should be kept alive because that's how DB pooling could take effect. Right?

Jir*_*vec 5

底线是——是的,它应该保持活力。如果您保持实例处于活动状态,则不会对性能造成任何影响。因为 Sequelize 实例(以及扩展的 ORM)将处理未来的连接。这还包括(正如您所指出的)池化。

连接

当涉及到池配置本身时,它会变得有点棘手。根据您的配置,池有一定量的“空间”可供使用 - 创建连接的限制、删除连接后的空闲持续时间等。我当然可以想象根本不需要保持连接活动的情况 -例如,公司的内部系统不会在一夜之间使用。

Sequelize ORM 为您提供了一组很好的选项,供您在配置连接池时进行选择。一般来说,您确实希望重用连接,因为建立新的连接非常昂贵 - 不仅是因为网络(例如授权,可能是代理等),而且还因为创建数据库连接时发生的内存分配(这就是为什么对每个请求重新连接并不是一个好主意..)。

然而,这一切都取决于您使用哪种数据库引擎(以及您的系统有多繁忙);例如,MySQL 可以缓存连接。当连接关闭时,它会返回到线程缓存而不是被丢弃(在一段时间内)。当新连接打开时,MySQL 将查找线程缓存,而不是尝试建立新连接。

您可能想要查看这些: