复制集(replica Set)或者副本集是MongoDB的核心高可用特性之一,它基于主节点的oplog日志持续传送到辅助节点,并重放得以实现主从节点一致。再结合心跳机制,当感知到主节点不可访问或宕机的情形下,辅助节点通过选举机制来从剩余的辅助节点中推选一个新的主节点从而实现自动切换。对于一个已经存在的MongoDB Replica Set集群,可以对其进行节点的增加,删除,以及修改节点属性等等。本文即是围绕这些进行描述。
有关MongoDB复制集概念及其搭建,可以参考:MongoDB 复制集(Replica Set)
一、节点的移除
//当前的演示环境
repSetTest:PRIMARY> db.version()
3.2.11
//主从节点
PRIMARY: localhost:27001
SECONDARY: localhost:27000
SECONDARY: localhost:27002
repSetTest:PRIMARY> rs.remove("localhost:27000")
{ "ok" : 1 }
//移除节点后的状态信息
repSetTest:PRIMARY> rs.status()
{
"set" : "repSetTest",
"date" : ISODate("2016-08-30T05:48:13.010Z"),
"myState" : 1,
"members" : [
{
"_id" : 1,
"name" : "localhost:27001",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 526,
"optime" : Timestamp(1472536085, 1),
"optimeDate" : ISODate("2016-08-30T05:48:05Z"),
"electionTime" : Timestamp(1472535890, 1),
"electionDate" : ISODate("2016-08-30T05:44:50Z"),
"configVersion" : 2,
"self" : true
},
{
"_id" : 2,
"name" : "localhost:27002",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 426,
"optime" : Timestamp(1472536085, 1),
"optimeDate" : ISODate("2016-08-30T05:48:05Z"),
"lastHeartbeat" : ISODate("2016-08-30T05:48:11.805Z"),
"lastHeartbeatRecv" : ISODate("2016-08-30T05:48:12.877Z"),
"pingMs" : 0,
"syncingTo" : "localhost:27001",
"configVersion" : 2
}
],
"ok" : 1
}
//移除后查看配置文件
//此时版本version为2,只有2个节点
repSetTest:PRIMARY> rs.config()
{
"_id" : "repSetTest",
"version" : 2,
"members" : [
{
"_id" : 1,
"host" : "localhost:27001",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"pr