本文主要是介绍mongodb配置replica set 主从,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简单点,单机不同端口两个节点,(官方推荐三个及以上的单数)一主一从:
mongod1.conf
systemLog:destination: filepath: /usr/local/var/log/mongodb/mongo.loglogAppend: true
storage:dbPath: /server/mongodb/data1
net:bindIp: 127.0.0.1port: 40000
replication:replSetName: rs-demo
mongod2.conf
systemLog:destination: filepath: /usr/local/var/log/mongodb/mongo.loglogAppend: true
storage:dbPath: /server/mongodb/data2
net:bindIp: 127.0.0.1port: 40001
replication:replSetName: rs-demo
分别启动两个mongd实例,
mongod --config mongod1.conf
mongod --config mongod2.conf
再开始第三个终端窗口,进入mongo客户端
mongo --port 40000
执行 rs.initiate()命令初始化replica set
> rs.initiate()
{"info2" : "no configuration specified. Using a default configuration for the set","me" : "MacBook-Pro-Work.local:40000","ok" : 1
}
成功,添加了MacBook-Pro-Work.local:40000节点,
执行rs.add命令添加另一节点:
rs-demo:SECONDARY> rs.add('MacBook-Pro-Work.local:40001')
{ "ok" : 1 }
搭建完成
进入主节点:
➜ ~ mongo --port 40001
MongoDB shell version: 3.2.22
connecting to: 127.0.0.1:40001/test
Server has startup warnings:
2020-11-26T00:59:56.082+0800 I CONTROL [initandlisten]
2020-11-26T00:59:56.082+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
rs-demo:PRIMARY>
进入从节点:
➜ mongodb mongo --port 40000
MongoDB shell version: 3.2.22
connecting to: 127.0.0.1:40000/test
Server has startup warnings:
2020-11-26T00:59:57.602+0800 I CONTROL [initandlisten]
2020-11-26T00:59:57.602+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
rs-demo:SECONDARY>
注意此时从节点不能读数据,
rs-demo:SECONDARY> show dbs;
2020-11-26T01:02:39.306+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435 } :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:781:19
shellHelper@src/mongo/shell/utils.js:671:15
@(shellhelp2):1:1
执行 rs.slaveOk()命令就可以读了
rs-demo:SECONDARY> rs.slaveOk()
配置mongoengine连接
from mongoengine import connect
connect = connect(host='mongodb://MacBook-Pro-Work.local:40000,MacBook-Pro-Work.local:40001/tumblelog?replicaSet=rs-demo')
这篇关于mongodb配置replica set 主从的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!