首页 > 代码库 > Mongodb复制集配置
Mongodb复制集配置
环境:
192.168.99.129 master
192.168.99.130 slave1
1、配置复制集
在两台服务器上分别执行
mongod --replSet "rs0"
执行mongo命令,先添加一台
rs.initiate( { _id : "rs0", members: [ { _id : 0, host : "master:27017" } ]})
再添加另外一台
rs.add("slave1")
执行rs.status()查看复制集节点的状态
rs0:PRIMARY> rs.status(){ "set" : "rs0", "date" : ISODate("2017-01-01T05:08:29.623Z"), "myState" : 1, "term" : NumberLong(3), "heartbeatIntervalMillis" : NumberLong(2000), "optimes" : { "lastCommittedOpTime" : { "ts" : Timestamp(1483247303, 1), "t" : NumberLong(3) }, "appliedOpTime" : { "ts" : Timestamp(1483247303, 1), "t" : NumberLong(3) }, "durableOpTime" : { "ts" : Timestamp(1483247303, 1), "t" : NumberLong(3) } }, "members" : [ { "_id" : 0, "name" : "master:27017", "health" : 1, "state" : 1, "stateStr" : "PRIMARY", "uptime" : 38, "optime" : { "ts" : Timestamp(1483247303, 1), "t" : NumberLong(3) }, "optimeDate" : ISODate("2017-01-01T05:08:23Z"), "infoMessage" : "could not find member to sync from", "electionTime" : Timestamp(1483247282, 1), "electionDate" : ISODate("2017-01-01T05:08:02Z"), "configVersion" : 2, "self" : true }, { "_id" : 1, "name" : "slave1:27017", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 33, "optime" : { "ts" : Timestamp(1483247303, 1), "t" : NumberLong(3) }, "optimeDurable" : { "ts" : Timestamp(1483247303, 1), "t" : NumberLong(3) }, "optimeDate" : ISODate("2017-01-01T05:08:23Z"), "optimeDurableDate" : ISODate("2017-01-01T05:08:23Z"), "lastHeartbeat" : ISODate("2017-01-01T05:08:29.007Z"), "lastHeartbeatRecv" : ISODate("2017-01-01T05:08:27.902Z"), "pingMs" : NumberLong(0), "syncingTo" : "master:27017", "configVersion" : 2 } ], "ok" : 1}
2、验证复制集
在主节点插入数据后,看从节点是否存在同样的数据,但在从节点执行查询数据库指令时抛错
rs0:SECONDARY> show dbs2016-12-31T20:49:59.362-0800 E QUERY [main] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435, "codeName" : "NotMasterNoSlaveOk"} :
因为从节点默认是不允许读写的,解决这个问题,有两种方式
在从节点上执行rs.slaveOk()
或者在主节点上执行db.getMongo().setSlaveOk()
在主节点上插入数据
rs0:PRIMARY> db.student.insert({"name":"xiaoming"})WriteResult({ "nInserted" : 1 })rs0:PRIMARY> db.student.find(){ "_id" : ObjectId("58688fa863a36c070316cd69"), "name" : "xiaoming" }
在从节点上查询
rs0:SECONDARY> db.student.find(){ "_id" : ObjectId("58688fa863a36c070316cd69"), "name" : "xiaoming" }
Mongodb复制集配置
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。