为了账号安全,请及时绑定邮箱和手机立即绑定

为什么建议不要在Node.js代码中的任何地方关闭MongoDB连接?

为什么建议不要在Node.js代码中的任何地方关闭MongoDB连接?

绝地无双 2019-11-14 14:48:08
考虑以下是Node.js代码:function My_function1(_params) {    db.once('open', function (err){     //Do some task 1});}function My_function2(_params) {    db.once('open', function (err){     //Do some task 2});}请参阅链接以获取最佳实践,该实践表明不要关闭任何连接https://groups.google.com/forum/#!topic/node-mongodb-native/5cPt84TUsVg我已经看到日志文件包含以下数据:Fri Jan 18 11:00:03 Trying to start Windows service 'MongoDB'Fri Jan 18 11:00:03 Service runningFri Jan 18 11:00:03 [initandlisten] MongoDB starting : pid=1592 port=27017 dbpath=\data\db\ 64-bit host=AMOL-KULKARNIFri Jan 18 11:00:03 [initandlisten] db version v2.2.1, pdfile version 4.5Fri Jan 18 11:00:03 [initandlisten] git version: d6...e0685521b8bc7b98fd1fab8cfeb5aeFri Jan 18 11:00:03 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49Fri Jan 18 11:00:03 [initandlisten] options: { config: "c:\mongodb\mongod.cfg", logpath: "c:\mongodb\log\mongo.log", service: true }Fri Jan 18 11:00:03 [initandlisten] journal dir=/data/db/journalFri Jan 18 11:00:03 [initandlisten] recover beginFri Jan 18 11:00:04 [initandlisten] recover lsn: 6624179Fri Jan 18 11:00:04 [initandlisten] recover /data/db/journal/j._0Fri Jan 18 11:00:04 [initandlisten] recover skipping application of section seq:59343 < lsn:6624179Fri Jan 18 11:00:04 [initandlisten] recover skipping application of section seq:118828 < lsn:6624179Fri Jan 18 11:00:04 [initandlisten] recover skipping application of section seq:238138 < lsn:6624179Fri Jan 18 11:00:04 [initandlisten] recover skipping application of section seq:835658 < lsn:6624179Fri Jan 18 11:00:04 [initandlisten] recover skipping application of section seq:955218 < lsn:6624179Fri Jan 18 11:00:04 [initandlisten] recover skipping application of section seq:3467218 < lsn:6624179通过打开多个连接而不是关闭多个连接,这是否在服务器上造成了开销?它是否在内部处理连接池?但是在MongoDB Docs中提到“这是不使用请求池的应用程序的正常行为”有人可以帮助我理解这一点吗?
查看完整描述

3 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

MongoDB将数据库连接池化以提高效率,因此在mongodb.log中打开许多连接并不罕见


但是,当应用程序完全关闭时,关闭所有连接很有用。此代码是执行此操作的最佳选择。


process.on('SIGINT', function() {

  mongoose.connection.close(function () {

    console.log('Mongoose disconnected on app termination');

    process.exit(0);

  });

});


查看完整回答
反对 回复 2019-11-14
  • 3 回答
  • 0 关注
  • 1088 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信