我希望在使用 Docker 和 Kubernetes 时通过 sidecar 自动设置 MongoDb 副本集的过程。
上述设置并不是很重要,归结为我需要能够调用 mongo 副本集命令(例如 rs.initiate()来自 Node 的
、rs.add('anotherserver')
、rs.conf()
、rs.reconfig()
等) .js 应用程序。
注意:它不一定来自 Node 应用程序,如果有人知道完成相同事情的另一种方法,请分享您的想法。
更新:我能够让这个工作,并让边车开源供其他人使用。
最佳答案
副本集管理助手是如何实现的?
rs.*
replica set admin helpers mongo
shell 中是 MongoDB 命令的包装器,您可以从任何驱动程序发送这些命令。
您可以通过引用 MongoDB 文档查看每个 shell 帮助程序包装了哪些命令:
-
rs.initiate()
为replSetInitiate
提供了一个包装器数据库命令。 -
rs.add()
提供了replSetReconfig
的一些功能的包装器。数据库命令和相应的 mongo shell helperrs.reconfig()
. -
rs.conf()
包裹replSetGetConfig
数据库命令。
请注意,mongo
shell 助手可能会对配置进行一些额外的验证或操作,因为它们旨在通过交互式 mongo
shell 使用。
您可以通过在 shell 中调用不带括号的命令来确认任何 shell 助手是如何实现的,例如:
> rs.initiate
function (c) { return db._adminCommand({ replSetInitiate: c }); }
从 Node.js 调用副本集数据库命令
等效的逻辑可以通过 Node.js 驱动 API 使用 command()
来实现。 :
// Rough equivalent of rs.initiate()
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
// Use the admin database for commands
var adminDb = db.admin();
// Default replica set conf
var conf = {};
adminDb.command({replSetInitiate: conf}, function(err, info) {
console.log(info);
});
});
Note: it doesn't have to be from a node application, if someone knows of another way of getting the same thing done, please share your thoughts.
您可以使用 --eval
命令调用 mongo
shell 来运行 shell 助手,而不是在 Node.js 中重新实现副本集助手(提示:包括--quiet
抑制不必要的消息)。
例如,从您的 Node 应用调用:
var exec = require('child_process').exec;
var rsAdmin = exec('mongo --eval "var res = rs.initiate(); printjson(res)" --quiet', function (error, stdout, stderr) {
// output is in stdout
console.log(stdout);
});
关于node.js - 我可以使用 MongoDb 驱动程序从 node.js 调用 rs.initiate() 和 rs.Add() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30041699/