副本集概述 副本集(Replica Set)是一組帶有故障轉移的 MongoDB 實例組成的集群,由一個主(Primary)伺服器和多個從(Secondary)伺服器構成。通過Replication,將數據的更新由Primary推送到其他實例上,在一定的延遲之後,每個MongoDB實例維護相同的數據 ...
副本集概述
-
副本集(Replica Set)是一組帶有故障轉移的 MongoDB 實例組成的集群,由一個主(Primary)伺服器和多個從(Secondary)伺服器構成。通過Replication,將數據的更新由Primary推送到其他實例上,在一定的延遲之後,每個MongoDB實例維護相同的數據集副本。通過維護冗餘的資料庫副本,能夠實現數據的異地備份,讀寫分離和自動故障轉移。
-
MongoDB 副本集中沒有固定的主節點,在啟動後,多個服務節點間將自動選舉產生一個主節點。該主節點被稱為primary,一個或多個從節點被稱為secondaries。primary基本上就是master節點,不同之處在於primary節點在不同時間可能是不同的伺服器。如果當前的主節點失效了,副本集中的其餘節點將會試圖選出一個新的主節點。
節點說明
MongoDB副本集架構通過部署多種節點來達到高可用和讀寫分離的效果,每個副本集實例包含一個主節點(Primary節點)、一個或多個從節點(Secondary節點)、隱藏節點(Hidden節點)、仲裁節點(Arbiter節點)和可選的一個或多個只讀節點(ReadOnly節點)。其中主節點、從節點和隱藏節點合起來統稱為“主備節點”。各節點的說明如下:
主節點(Primary節點)
- 負責執行和響應數據讀寫請求。每個副本集實例中只能有一個主節點。主節點將其數據集的所有更改記錄在其操作日誌(即oplog小於50 GB)中。
從節點(Secondary節點)
-
通過操作日誌(oplog)同步主節點的數據,可在主節點故障時通過選舉成為新的主節點,保障高可用。
-
通過從節點的連接地址進行連接時,只能讀取數據不能寫入數據。
-
從節點具有高可用保障,即某個從節點故障時,系統會自動將其與隱藏節點切換,若未自動切換,您可以自行切換,從節點的連接地址保持不變。
觸發節點的角色切換後,會產生1次30秒內的連接閃斷,建議您在業務低峰期操作或確保應用具備重連機制。
隱藏節點(Hidden節點)
-
通過操作日誌(oplog)同步主節點的數據,可在從節點故障時接替該故障節點成為新的從節點,也可在只讀節點故障時接替該故障節點成為新的只讀節點,保障高可用。
-
隱藏節點僅用作高可用,對客戶端不可見。
-
隱藏節點不在“主節點的備用列表”中,不會被選舉為主節點,但會參與投票選舉主節點。
-
每個副本集實例中只能有一個隱藏節點。
仲裁節點(Arbiter節點)
-
仲裁節點,只是用來投票,且投票的權重只能為1,不複製數據,也不能提升為primary。
-
仲裁節點常用於節點數量是偶數的副本集中。
-
通常將Arbiter部署在業務伺服器上,切忌將其部署在Primary節點或Secondary節點伺服器上。
只讀節點(ReadOnly節點)
-
通過操作日誌(oplog)從延遲最低的主節點或從節點同步數據,應用於有大量讀請求的場景,以減輕主節點和從節點的訪問壓力。兩個或以上只讀節點可以使用ReadOnly Connection String URI連接實現讀請求負載均衡。
-
只讀節點具有高可用保障,即某個只讀節點故障時,系統會自動將其與隱藏節點切換,若未自動切換,您可以自行切換,只讀節點的連接地址保持不變。
觸發節點的角色切換後,會產生1次30秒內的連接閃斷,建議您在業務低峰期操作或確保應用具備重連機制。
-
只讀節點具有獨立的連接地址,適合獨立系統直連訪問,與已有主從節點的連接互不幹擾。
-
只讀節點不在“主節點的備用列表”中,不會被選舉為主節點,也不會參與投票選舉主節點。
副本集部署架構
-
MongoDB 6.x 官方介紹副本節點最少為3台,建議副本集成員為奇數,最多50個副本節點,最多7個節點參與選舉。
-
限制副本節點的數量,主要是因為一個集群中過多的副本節點,增加了複製的成本,反而拖累了集群的整體性能。
-
太多的副本節點參與選舉,也會增加選舉的時間。而官方建議奇數的節點,是為了避免腦裂的發生。
副本集搭建過程
環境準備
主機名 | IP地址 | 成員 |
---|---|---|
MongoDB-Master | 172.16.70.181 | 主節點 |
MongoDB-Slave01 | 172.16.70.182 | 從節點 |
MongoDB-Slave02 | 172.16.70.183 | 從節點 |
# 三個節點統一設置,這裡以 MongoDB-Master 為例
[root@MongoDB-Master ~]# cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)
[root@MongoDB-Master ~]# uname -r
3.10.0-1160.el7.x86_64
# 修改ulimit 系統資源限制
[root@MongoDB-Master ~]# cat /etc/security/limits.conf
....末行追加以下內容....
root soft nproc 65535
root hard nproc 65535
root hard nofile 65535
root soft nofile 65535
[root@MongoDB-Master ~]# setenforce 0
[root@MongoDB-Master ~]# sed -i.bak '7s/enforcing/disabled/' /etc/selinux/config
[root@MongoDB-Master ~]# systemctl stop firewalld
[root@MongoDB-Master ~]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: man:firewalld(1)
安裝 MongoDB 6.0
# 使用Yum方式安裝當前最新穩定版本,這裡以 MongoDB-Master 為例,其他兩從節點一樣操作。
[root@MongoDB-Master ~]# cat /etc/yum.repos.d/mongodb-org-6.0.repo
[mongodb-org-6.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
[root@MongoDB-Master ~]# yum install -y mongodb-org
=========================================================================================================
# 如要安裝特定版本的 MongoDB,請單獨指定每個組件包並將版本號附加到包名稱,例如
yum install -y mongodb-org-6.0.10 mongodb-org-database-6.0.10 mongodb-org-server-6.0.10 mongodb-org-mongos-6.0.10 mongodb-org-tools-6.0.10
# yum當更新版本可用時升級軟體包。為防止意外升級,請固定包。要固定包,請將以下exclude指令添加到您的/etc/yum.conf文件中
exclude=mongodb-org,mongodb-org-database,mongodb-org-server,mongodb-mongosh,mongodb-org-mongos,mongodb-org-tools
=========================================================================================================
# 查看安裝版本
[root@MongoDB-Master ~]# mongod --version
db version v6.0.11
Build Info: {
"version": "6.0.11",
"gitVersion": "f797f841eaf1759c770271ae00c88b92b2766eed",
"openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
"modules": [],
"allocator": "tcmalloc",
"environment": {
"distmod": "rhel70",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}
# 修改配置文件 (bindIp: 127.0.0.1,172.16.70.181)
[root@MongoDB-Master ~]# grep -Ev "^$" /etc/mongod.conf
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# Where and how to store data.
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
# engine:
# wiredTiger:
# how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
# network interfaces
net:
port: 27017
# 註意:本機的ip地址。否則後面進行副本集初始化的時候可能會失敗!
bindIp: 127.0.0.1,172.16.70.181 # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
#security:
#operationProfiling:
replication:
# 定義副本集名稱
replSetName: testrs0
#sharding:
## Enterprise-Only Options
#auditLog:
#snmp:
# 確保運行MongoDB的用戶有權訪問相關目錄
[root@MongoDB-Master ~]# grep mongo /etc/passwd
mongod:x:997:996:mongod:/var/lib/mongo:/bin/false
[root@MongoDB-Master ~]# ls -ld /var/log/mongodb/mongod.log /var/lib/mongo
drwxr-xr-x 4 mongod mongod 4096 Oct 20 10:25 /var/lib/mongo
-rw-r----- 1 mongod mongod 171974 Oct 20 10:22 /var/log/mongodb/mongod.log
# 啟動MongoDB
[root@MongoDB-Master ~]# systemctl start mongod && systemctl enable mongod
[root@MongoDB-Master ~]# systemctl list-units | grep mongod
mongod.service loaded active running MongoDB Database Server
[root@MongoDB-Master ~]# ps axu | grep mongod
mongod 1563 1.8 2.4 2805700 97536 ? Ssl 11:26 0:01 /usr/bin/mongod -f /etc/mongod.conf
root 1703 0.0 0.0 112808 968 pts/0 S+ 11:27 0:00 grep --color=auto mongod
[root@MongoDB-Master ~]# netstat -ntpl | grep mongod
tcp 0 0 172.16.70.181:27017 0.0.0.0:* LISTEN 1563/mongod
tcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 1563/mongod
[root@MongoDB-Master ~]# ls -l /tmp/mongodb-27017.sock
srwx------ 1 mongod mongod 0 Oct 20 11:26 /tmp/mongodb-27017.sock
部署副本集
這裡的_id
與配置文件mongod.conf中replSetName
保持一致。
# 在任意節點執行 rs.initiate,這裡選擇在MongoDB-Master操作初始化。
[root@MongoDB-Master ~]# mongosh
test> rs.initiate( {
... _id : "testrs0",
... members: [
... { _id: 0, host: "172.16.70.181:27017" },
... { _id: 1, host: "172.16.70.182:27017" },
... { _id: 2, host: "172.16.70.183:27017" }
... ]
... })
{ ok: 1 }
# 查看副本集配置,確保只有一個主節點
testrs0 [direct: primary] test> rs.conf()
{
_id: 'testrs0',
version: 1,
term: 1,
members: [
{
_id: 0,
host: '172.16.70.181:27017',
arbiterOnly: false, # 是否為仲裁者,預設為false
buildIndexes: true, # 是否為構建索引成員
hidden: false, # 是否為隱藏成員
priority: 1, # 範圍0~1000,預設為1,值大為主節點primary,值為0則不能成為primay(仲裁)
tags: {},
secondaryDelaySecs: Long("0"), # 從節點複製延遲時間,單位秒s
votes: 1 # 選舉投票的數量
},
{
_id: 1,
host: '172.16.70.182:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 1, # 預設為1
tags: {},
secondaryDelaySecs: Long("0"),
votes: 1
},
{
_id: 2,
host: '172.16.70.183:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 1, # 預設為1
tags: {},
secondaryDelaySecs: Long("0"),
votes: 1
}
],
protocolVersion: Long("1"),
writeConcernMajorityJournalDefault: true,
settings: {
chainingAllowed: true,
heartbeatIntervalMillis: 2000,
heartbeatTimeoutSecs: 10,
electionTimeoutMillis: 10000,
catchUpTimeoutMillis: -1,
catchUpTakeoverDelayMillis: 30000,
getLastErrorModes: {},
getLastErrorDefaults: { w: 1, wtimeout: 0 },
replicaSetId: ObjectId("6531f7207c8f661d6f787810")
}
}
testrs0 [direct: primary] test> rs.status()
{
set: 'testrs0', # 副本集名稱
date: ISODate("2023-10-20T04:06:56.352Z"), # 當前時間
myState: 1, # 成員的副本狀態(0~10);常見 1:PRIMARY,2:SECONDARY,7:ARBITER,8:DOWN
term: Long("2"), # 獲得選舉的票數
syncSourceHost: '', # 實例同步成員的主機名
syncSourceId: -1, # 實例同成員名稱
heartbeatIntervalMillis: Long("2000"), # 心跳頻率,毫秒ms
majorityVoteCount: 2, # 被選舉為主節點所需要的票數
writeMajorityCount: 2, # 滿足寫操作所需要的票數
votingMembersCount: 3, # 該副本集中成員數量
writableVotingMembersCount: 3, # 有投票權的成員數量
optimes: {
lastCommittedOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
lastCommittedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
readConcernMajorityOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
appliedOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
durableOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z")
},
lastStableRecoveryTimestamp: Timestamp({ t: 1697774793, i: 1 }),
electionCandidateMetrics: {
lastElectionReason: 'stepUpRequestSkipDryRun',
lastElectionDate: ISODate("2023-10-20T04:04:37.304Z"),
electionTerm: Long("2"),
lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1697774676, i: 1 }), t: Long("1") },
lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1697774676, i: 1 }), t: Long("1") },
numVotesNeeded: 2,
priorityAtElection: 1,
electionTimeoutMillis: Long("10000"),
priorPrimaryMemberId: 1,
numCatchUpOps: Long("0"),
newTermStartDate: ISODate("2023-10-20T04:04:37.311Z"),
wMajorityWriteAvailabilityDate: ISODate("2023-10-20T04:04:38.331Z")
},
electionParticipantMetrics: {
votedForCandidate: true,
electionTerm: Long("1"),
lastVoteDate: ISODate("2023-10-20T03:42:36.120Z"),
electionCandidateMemberId: 1,
voteReason: '',
lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1697773344, i: 1 }), t: Long("-1") },
maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1697773344, i: 1 }), t: Long("-1") },
priorityAtElection: 1
},
members: [
{
_id: 0, # 副本集中節點編號
name: '172.16.70.181:27017', # 伺服器名稱及埠號
health: 1, # 健康狀態;1為正常,0為異常
state: 1, # 當前狀態;數值小為primary,數值大為secondary
stateStr: 'PRIMARY', # 主節點(PRIMARY),從節點(SECONDARY)
uptime: 2424, # 線上時間(秒)
optime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") }, # 最後一次應用日誌(oplog)信息
optimeDate: ISODate("2023-10-20T04:06:47.000Z"), # 最後一次應用日誌(oplog)時間
lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"), # 該成員在主節點上應用的最後一次操作的時間
lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z"), # 最後一次寫入成員日誌的操作首次在主節點上應用時的時間
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
electionTime: Timestamp({ t: 1697774677, i: 1 }), # primary從操作日誌選舉時間戳信息
electionDate: ISODate("2023-10-20T04:04:37.000Z"), # 被選定為primary的時間
configVersion: 1, # 副本集版本
configTerm: 2,
self: true,
lastHeartbeatMessage: ''
},
{
_id: 1,
name: '172.16.70.182:27017',
health: 1,
state: 2, # 數值小為primary,數值大為secondary
stateStr: 'SECONDARY', # 從節點
uptime: 84,
optime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
optimeDurable: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
optimeDate: ISODate("2023-10-20T04:06:47.000Z"),
optimeDurableDate: ISODate("2023-10-20T04:06:47.000Z"),
lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z"),
lastHeartbeat: ISODate("2023-10-20T04:06:55.647Z"),
lastHeartbeatRecv: ISODate("2023-10-20T04:06:55.575Z"),
pingMs: Long("0"),
lastHeartbeatMessage: '',
syncSourceHost: '172.16.70.183:27017',
syncSourceId: 2,
infoMessage: '',
configVersion: 1,
configTerm: 2
},
{
_id: 2,
name: '172.16.70.183:27017',
health: 1,
state: 2, # 數值小為primary,數值大為secondary
stateStr: 'SECONDARY', # 從節點
uptime: 1471,
optime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
optimeDurable: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
optimeDate: ISODate("2023-10-20T04:06:47.000Z"),
optimeDurableDate: ISODate("2023-10-20T04:06:47.000Z"),
lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z"),
lastHeartbeat: ISODate("2023-10-20T04:06:55.561Z"),
lastHeartbeatRecv: ISODate("2023-10-20T04:06:54.598Z"),
pingMs: Long("0"),
lastHeartbeatMessage: '',
syncSourceHost: '172.16.70.181:27017',
syncSourceId: 0,
infoMessage: '',
configVersion: 1,
configTerm: 2
}
],
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1697774807, i: 1 }),
signature: {
hash: Binary.createFromBase64("AAAAAAAAAAAAAAAAAAAAAAAAAAA=", 0),
keyId: Long("0")
}
},
operationTime: Timestamp({ t: 1697774807, i: 1 })
}
testrs0 [direct: primary] test>
複製功能測試
# 在主節點(172.16.70.181)上新增mydb庫,並創建myColl文檔
[root@MongoDB-Master ~]# mongosh
testrs0 [direct: primary] test>
testrs0 [direct: primary] test> show dbs
admin 80.00 KiB
config 208.00 KiB
local 484.00 KiB
testrs0 [direct: primary] test> use mydb
switched to db mydb
testrs0 [direct: primary] mydb> db.myColl.insertOne({ name: "zhang" })
{
acknowledged: true,
insertedId: ObjectId("65361759be7d5c1abe9d83ee")
}
testrs0 [direct: primary] mydb> db.myColl.find()
[ { _id: ObjectId("65361759be7d5c1abe9d83ee"), name: 'zhang' } ]
# 在從節點(172.16.70.182/183)上查看複製同步數據結果
[root@MongoDB-Slave01 ~]# mongosh
testrs0 [direct: secondary] test> use mydb
switched to db mydb
testrs0 [direct: secondary] mydb> show collections
myColl
testrs0 [direct: secondary] mydb> db.myColl.find()
MongoServerError: not primary and secondaryOk=false - consider using db.getMongo().setReadPref() or readPreference in the connection string
# MongoServerError 報錯!
# 這是因為mongodb預設是從主節點讀寫數據的,副本節點上不允許讀,需要設置副本節點可以讀
testrs0 [direct: secondary] mydb> db.getMongo().setReadPref('secondary')
testrs0 [direct: secondary] mydb> db.myColl.find()
[ { _id: ObjectId("65361759be7d5c1abe9d83ee"), name: 'zhang' } ]
# 此時,主節點數據已經同步到從節點上
故障轉移功能測試
# 假設主節點(172.16.70.181)故障
[root@MongoDB-Master ~]# systemctl stop mongod
[root@MongoDB-Master ~]# netstat -ntpl | grep mongod
# 登錄從節點查看副本集狀態
[root@MongoDB-Slave01 ~]# mongosh
testrs0 [direct: primary] test> rs.status()
{
set: 'testrs0',
date: ISODate("2023-10-23T07:55:53.369Z"),
myState: 1,
term: Long("2"),
syncSourceHost: '',
syncSourceId: -1,
heartbeatIntervalMillis: Long("2000"),
majorityVoteCount: 2,
writeMajorityCount: 2,
votingMembersCount: 3,
writableVotingMembersCount: 3,
optimes: {
lastCommittedOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
lastCommittedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
readConcernMajorityOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
appliedOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
durableOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
lastAppliedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
lastDurableWallTime: ISODate("2023-10-23T07:55:43.519Z")
},
lastStableRecoveryTimestamp: Timestamp({ t: 1698047693, i: 1 }),
electionCandidateMetrics: {
lastElectionReason: 'stepUpRequestSkipDryRun',
lastElectionDate: ISODate("2023-10-23T07:51:13.449Z"),
electionTerm: Long("2"),
lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1698047468, i: 1 }), t: Long("1") },
lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1698047468, i: 1 }), t: Long("1") },
numVotesNeeded: 2,
priorityAtElection: 1,
electionTimeoutMillis: Long("10000"),
priorPrimaryMemberId: 0,
numCatchUpOps: Long("0"),
newTermStartDate: ISODate("2023-10-23T07:51:13.456Z"),
wMajorityWriteAvailabilityDate: ISODate("2023-10-23T07:51:14.459Z")
},
electionParticipantMetrics: {
votedForCandidate: true,
electionTerm: Long("1"),
lastVoteDate: ISODate("2023-10-23T07:47:58.216Z"),
electionCandidateMemberId: 0,
voteReason: '',
lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1698047267, i: 1 }), t: Long("-1") },
maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1698047267, i: 1 }), t: Long("-1") },
priorityAtElection: 1
},
members: [
{
_id: 0,
name: '172.16.70.181:27017',
health: 0,
state: 8,
stateStr: '(not reachable/healthy)',
uptime: 0,
optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
optimeDate: ISODate("1970-01-01T00:00:00.000Z"),
optimeDurableDate: ISODate("1970-01-01T00:00:00.000Z"),
lastAppliedWallTime: ISODate("2023-10-23T07:51:14.906Z"),
lastDurableWallTime: ISODate("2023-10-23T07:51:14.906Z"),
lastHeartbeat: ISODate("2023-10-23T07:55:52.462Z"),
lastHeartbeatRecv: ISODate("2023-10-23T07:51:28.493Z"),
pingMs: Long("0"),
lastHeartbeatMessage: 'Error connecting to 172.16.70.181:27017 :: caused by :: Connection refused', # 提示: Error
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
configVersion: 1,
configTerm: 2
},
{
_id: 1,
name: '172.16.70.182:27017',
health: 1,
state: 1,
stateStr: 'PRIMARY',
uptime: 1005,
optime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
optimeDate: ISODate("2023-10-23T07:55:43.000Z"),
lastAppliedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
lastDurableWallTime: ISODate("2023-10-23T07:55:43.519Z"),
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
electionTime: Timestamp({ t: 1698047473, i: 1 }),
electionDate: ISODate("2023-10-23T07:51:13.000Z"),
configVersion: 1,
configTerm: 2,
self: true,
lastHeartbeatMessage: ''
},
{
_id: 2,
name: '172.16.70.183:27017',
health: 1,
state: 2,
stateStr: 'SECONDARY',
uptime: 486,
optime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
optimeDurable: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
optimeDate: ISODate("2023-10-23T07:55:43.000Z"),
optimeDurableDate: ISODate("2023-10-23T07:55:43.000Z"),
lastAppliedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
lastDurableWallTime: ISODate("2023-10-23T07:55:43.519Z"),
lastHeartbeat: ISODate("2023-10-23T07:55:52.043Z"),
lastHeartbeatRecv: ISODate("2023-10-23T07:55:52.568Z"),
pingMs: Long("0"),
lastHeartbeatMessage: '',
syncSourceHost: '172.16.70.182:27017',
syncSourceId: 1,
infoMessage: '',
configVersion: 1,
configTerm: 2
}
],
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1698047743, i: 1 }),
signature: {
hash: Binary.createFromBase64("AAAAAAAAAAAAAAAAAAAAAAAAAAA=", 0),
keyId: Long("0")
}
},
operationTime: Timestamp({ t: 1698047743, i: 1 })
}
testrs0 [direct: primary] test>
# 此次,從節點(172.16.70.182)經過選舉後,成為新的主節點。
# 原主節點(172.16.70.181)故障恢復後,將成為新的主節點(172.16.70.182)的從節點。
# 如果想實例預設成為主節點,可設置更高優先順序priority(預設優先順序為1,m值是0~1000之間的數字,數字越大優先順序越高,m=0,則此節點永遠不能成為主節點)
# 即先移除rs.remove("ip:port"),再新增rs.add( { host: "ip:port", priority: Num } )
更改副本集優先順序
# 查看當前副本集配置
rs.conf()
# n為 _id 值,從0開始為第一個節點,1為第二個節點,....
# 預設優先順序為1,m值是0~1000之間的數字,數字越大優先順序越高,m=0,則此節點永遠不能成為主節點(仲裁)
cfg.members[n].priority = m
# 重新配置當前副本集
rs.reconfig(cfg)
新增副本集成員
# 必須在主節點上操作
# 新增具有預設投票和優先順序的成員到副本集
rs.add( { host: "mongodbd4.example.net:27017" } )
rs.add( "mongodbd4.example.net:27017" )
# 新增優先順序0的成員到副本集
rs.add( { host: "mongodbd4.example.net:27017", priority: 0 } )
# 新增仲裁者成員到副本集
rs.add( { host: "mongodb3.example.net:27017", arbiterOnly: true } )
rs.add("mongodb3.example.net:27017", true)
刪除副本成員
rs.remove("mongod3.example.net:27017")
rs.remove("mongod3.example.net")
替換副本集成員
cfg = rs.conf()
cfg.members[0].host = "mongo2.example.net"
rs.reconfig(cfg)
********** 如果您認為這篇文章還不錯或者有所收穫,請點擊右下角的【推薦】/【贊助】按鈕,因為您的支持是我繼續寫作,分享的最大動力! **********作者:上古南城
出處:https://www.cnblogs.com/zhangwencheng
版權:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出 原文鏈接