【问题标题】:How do I cleanly shutdown mongodb from node.js?如何从 node.js 干净地关闭 mongodb?
【发布时间】:2018-05-06 08:42:03
【问题描述】:

我将 mongodb 作为 node.js 的子进程运行,并且需要按需关闭和重新启动。使用 Child_Process.kill("SIGINT") 似乎是正确的方法,但它使 mongo 处于混乱状态,直到修复(或锁定文件被删除)才会重新启动。有没有更好的方法来做到这一点?

谢谢, 安迪

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    执行kill("SIGINT") 会导致数据库在不执行所需步骤的情况下关闭,并可能导致数据文件损坏。所以我不建议这样做。

    停止数据库的正常方法是从 mongodb shell 发送命令 { "shutdown" : 1 } 或 db.shutdownServer(),但我不知道如何从 node.js 驱动程序执行此操作。

    【讨论】:

    • 来自 Mongodb 文档:发送 Unix INT 或 TERM 信号 您可以在类 Unix 系统上使用 SIGINT 或 SIGTERM 信号彻底停止 mongod。 ^C、“kill -2 PID”或 kill -15 PID 都可以。如果 mongod 未使用 --journal 选项运行,则发送 KILL 信号 kill -9 可能会造成损坏。 (在这种情况下,运行repairDatabase命令。)windows是否有等效的操作?
    • 更正:根据stop mongod processes 文档,通过向 mongod 发送 SIGINT(信号 2)或 SIGTERM(信号 15,默认信号)来停止 mongod 是安全 )。这些是关闭 mongo 的一系列不同安全方法中列出的。
    【解决方案2】:

    你可以试试这样的:

    var MongoClient = require('mongodb').MongoClient;
    MongoClient.connect("mongodb://localhost:27017/admin", function(err, db) {
    	if (err) {
    		console.log('mongodb is not running');
    		process.exit(0);
    	}
    	else {
    		db.command({
    			shutdown : 1
    		}, function(err, result) {
    			console.log('shutting down mongodb - ', err.message);
    			process.exit(0);
    		});
    	}
    });

    【讨论】:

      【解决方案3】:

      你可以在 mac 上使用 nodeJS 结束一个 mongodb 进程

      1) 将下面的脚本保存到 script.js

      'use strict'
      const exec = require('child_process').execSync;
      function killport(port) {
          var processId = null
          try {
              processId = exec(`lsof -t -i:${port}`);
          } catch (e) {
              console.log("could not catch");
          }
          if (processId !== null) { // if exists kill
             try{
                 if(exec(`kill ${processId}`)){
                     console.log("closed");
                  }
             } catch(e){
                  console.log("error executing");
             }
           }
        }
       killport(27017); 
      

      2) 运行节点脚本.js

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多