开启副本集
修改配置文件/etc/mongod.conf
replication:
replSetName: main
重启mongod相关服务systemctl restart mongod
注意:每个在副本集中的成员,无论主副replSetName都一样,表示一个副本集的名称
如果添加的节点的replSetName和主节点不一致,则会报错:
添加到副本集
rs.add("ip:port")
查看副本集节点状态
main:PRIMARY> rs.status()
{
“set” : “main”,
“date” : ISODate(“2023-06-15T03:57:43.199Z”),
“myState” : 1,
“term” : NumberLong(2),
“syncingTo” : “”,
“syncSourceHost” : “”,
“syncSourceId” : -1,
“heartbeatIntervalMillis” : NumberLong(2000),
“optimes” : {
“lastCommittedOpTime” : {
“ts” : Timestamp(1686801429, 1),
“t” : NumberLong(2)
},
“appliedOpTime” : {
“ts” : Timestamp(1686801459, 1),
“t” : NumberLong(2)
},
“durableOpTime” : {
“ts” : Timestamp(1686801459, 1),
“t” : NumberLong(2)
}
},
“lastStableCheckpointTimestamp” : Timestamp(1686801429, 1),
“electionCandidateMetrics” : {
“lastElectionReason” : “electionTimeout”,
“lastElectionDate” : ISODate(“2023-06-15T03:50:39.691Z”),
“electionTerm” : NumberLong(2),
“lastCommittedOpTimeAtElection” : {
“ts” : Timestamp(0, 0),
“t” : NumberLong(-1)
},
“lastSeenOpTimeAtElection” : {
“ts” : Timestamp(1686644734, 1),
“t” : NumberLong(1)
},
“numVotesNeeded” : 1,
“priorityAtElection” : 1,
“electionTimeoutMillis” : NumberLong(10000),
“newTermStartDate” : ISODate(“2023-06-15T03:50:39.693Z”),
“wMajorityWriteAvailabilityDate” : ISODate(“2023-06-15T03:50:39.748Z”)
},
“members” : [
{
“_id” : 0,
“name” : “yx03:9917”,
“health” : 1,
“state” : 1,
“stateStr” : “PRIMARY”,
“uptime” : 425,
“optime” : {
“ts” : Timestamp(1686801459, 1),
“t” : NumberLong(2)
},
“optimeDate” : ISODate(“2023-06-15T03:57:39Z”),
“syncingTo” : “”,
“syncSourceHost” : “”,
“syncSourceId” : -1,
“infoMessage” : “”,
“electionTime” : Timestamp(1686801039, 1),
“electionDate” : ISODate(“2023-06-15T03:50:39Z”),
“configVersion” : 2,
“self” : true,
“lastHeartbeatMessage” : “”
},
{
“_id” : 1,
“name” : “yx03:9928”,
“health” : 1,
“state” : 0,
“stateStr” : “STARTUP”,
“uptime” : 33,
“optime” : {
“ts” : Timestamp(0, 0),
“t” : NumberLong(-1)
},
“optimeDurable” : {
“ts” : Timestamp(0, 0),
“t” : NumberLong(-1)
},
“optimeDate” : ISODate(“1970-01-01T00:00:00Z”),
“optimeDurableDate” : ISODate(“1970-01-01T00:00:00Z”),
“lastHeartbeat” : ISODate(“2023-06-15T03:57:42.408Z”),
“lastHeartbeatRecv” : ISODate(“1970-01-01T00:00:00Z”),
“pingMs” : NumberLong(23),
“lastHeartbeatMessage” : “”,
“syncingTo” : “”,
“syncSourceHost” : “”,
“syncSourceId” : -1,
“infoMessage” : “”,
“configVersion” : -2
}
],
“ok” : 1,
“operationTime” : Timestamp(1686801459, 1),
“$clusterTime” : {
“clusterTime” : Timestamp(1686801459, 1),
“signature” : {
“hash” : BinData(0,“AAAAAAAAAAAAAAAAAAAAAAAAAAA=”),
“keyId” : NumberLong(0)
}
}
}
一些常见的错误
解决方案
- 删除节点
rs.remove(“ip1:port”)
- 重启mongo服务端
- 客户端重新配置:
conf=
{
“_id” : “main”,
“protocolVersion” : 1,
“members” : [
{ “_id” : 0, “host” : “ip1:port”,“priority”:5 },
{ “_id” : 1, “host” : “ip2:port”,“priority”:1 }
]
}
rs.reconfig(conf, {force:true});
rs.initiate(conf);
- 删除db目录下的文件重配置主副