[root@redhat7_6 ~]# netstat -anpt | grep 'mongod'
[root@redhat7_6 ~]# mongo --port 27017
> cfg={"_id":"kgcrs","members":[{"_id":0,"host":"192.168.100.76:27017","priority":100},{"_id":1,"host":"192.168.100.76:27018","priority":100},{"_id":2,"host":"192.168.100.76:27019","priority":0},{"_id":3,"host":"192.168.100.76:27020","arbiterOnly":true}]} #定义两个主节点,一个被动节点,一个仲裁节点> rs.initiate(cfg) #初始化复制集> kgcrs:PRIMARY> rs.isMaster() #查看群集状态
{
"hosts" : [ #标准节点
"192.168.100.76:27017",
"192.168.100.76:27018"
],
"passives" : [ #被动节点
"192.168.100.76:27019"
],
"arbiters" : [ #仲裁节点
"192.168.100.76:27020"
],
"setName" : "kgcrs",
"setVersion" : 1,
"ismaster" : true,
"secondary" : false,
"primary" : "192.168.100.76:27017",
"me" : "192.168.100.76:27017",
"electionId" : ObjectId("7fffffff0000000000000001"),
}
……
kgcrs:PRIMARY> use testDB #进入或创建库
kgcrs:PRIMARY> db.t1.insert({"id":1,"name":"Tom"}) #插入数据
kgcrs:PRIMARY> db.t1.insert({"id":2,"name":"Jack"})
kgcrs:PRIMARY> db.t1.find() #查看集合
{ "_id" : ObjectId("5b95c4c915740fa3d0077e8d"), "id" : 1, "name" : "Tom" }
{ "_id" : ObjectId("5b95c4d715740fa3d0077e8e"), "id" : 2, "name" : "Jack" }
kgcrs:PRIMARY> db.t1.update({"id":2},{"$set":{"name":"Bob"}}) #修改数据
kgcrs:PRIMARY> db.t1.remove({"id":2}) #移除数据
kgcrs:PRIMARY> show dbs
kgcrs:PRIMARY> use local #进入local库
kgcrs:PRIMARY> show collections
kgcrs:PRIMARY> db.oplog.rs.find() #注意查看每个文档都代表主节点上执行的一个操作,oplog会包含所有对数据有修改的操作(查询操作不会记录)
[root@redhat7_6 ~]# /etc/init.d/mongodb mongod1 stop #关闭01节点服务器
[root@redhat7_6 ~]# mongo --port 27018
kgcrs:PRIMARY> rs.status() #查看复制状态
3、模拟主节点02故障(端口27018)[root@redhat7_6 ~]# /etc/init.d/mongodb mongod2 stop
[root@redhat7_6 ~]# mongo --port 27019 #进入第三个实例
[root@redhat7_6 ~]# /etc/init.d/mongodb mongod1 start #第一个先启动实例1,成为主节点。可以进行人为控制
[root@redhat7_6 ~]# /etc/init.d/mongodb mongod2 start
kgcrs:PRIMARY> rs.status()
四、MongoDB复制集管理 1、配置允许在从节点读取数据 1).查看实例1服务[root@redhat7_6 ~]# mongo --port 27017
kgcrs:PRIMARY> show dbs
kgcrs:PRIMARY> use testDB
kgcrs:PRIMARY> db.t1.find() #查询集合数据
{ "_id" : ObjectId("5b98d55d06a599fff182be6d"), "id" : 1, "name" : "Tom" }
[root@redhat7_6 ~]# mongo --port 27018
kgcrs:SECONDARY> rs.slaveOk() #允许默认从节点读取数据
kgcrs:SECONDARY> show dbs
……
testDB 0.000GB #读取成功
kgcrs:SECONDARY> use testDB
kgcrs:SECONDARY> db.t1.find()
kgcrs:SECONDARY> rs.help() #查看命令帮助kgcrs:SECONDARY> rs.printReplicationInfo()
configured oplog size: 990MB #oplog文件大小
log length start to end: 7688secs (2.14hrs) #日志启用的时间段。单位:秒
oplog first event time: Wed Sep 12 2018 16:50:59 GMT+0800 (CST) #第一个事务日志的产生时间
oplog last event time: Wed Sep 12 2018 18:59:07 GMT+0800 (CST) #第一个事务日志的结束时间
now: Wed Sep 12 2018 18:59:16 GMT+0800 (CST) #当前时间kgcrs:SECONDARY> rs.printSlaveReplicationInfo() #可以通过下面IP、端口发现,仲裁节点不具备数据复制
source: 192.168.100.76:27018 #从库的IP及端口
syncedTo: Wed Sep 12 2018 18:59:27 GMT+0800 (CST) #目前的同步情况,延迟了多久等信息
0 secs (0 hrs) behind the primary
source: 192.168.100.76:27019
syncedTo: Wed Sep 12 2018 18:59:27 GMT+0800 (CST)
0 secs (0 hrs) behind the primary