搭建 MongoDB (v6.0) 副本集记录

打印 上一主题 下一主题

主题 560|帖子 560|积分 1680

副本集概述


  • 副本集(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-Master172.16.70.181主节点MongoDB-Slave01172.16.70.182从节点MongoDB-Slave02172.16.70.183从节点
  1. # 三个节点统一设置,这里以 MongoDB-Master 为例
  2. [root@MongoDB-Master ~]# cat /etc/redhat-release
  3. CentOS Linux release 7.9.2009 (Core)
  4. [root@MongoDB-Master ~]# uname -r
  5. 3.10.0-1160.el7.x86_64
  6. # 修改ulimit 系统资源限制
  7. [root@MongoDB-Master ~]# cat /etc/security/limits.conf
  8. ....末行追加以下内容....
  9. root    soft    nproc   65535
  10. root    hard    nproc   65535
  11. root    hard    nofile  65535
  12. root    soft    nofile  65535
  13. [root@MongoDB-Master ~]# setenforce 0
  14. [root@MongoDB-Master ~]# sed -i.bak '7s/enforcing/disabled/' /etc/selinux/config
  15. [root@MongoDB-Master ~]# systemctl stop firewalld
  16. [root@MongoDB-Master ~]# systemctl status firewalld
  17. ● firewalld.service - firewalld - dynamic firewall daemon
  18.    Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
  19.    Active: inactive (dead)
  20.      Docs: man:firewalld(1)
复制代码
安装 MongoDB 6.0
  1. # 使用Yum方式安装当前最新稳定版本,这里以 MongoDB-Master 为例,其他两从节点一样操作。
  2. [root@MongoDB-Master ~]# cat /etc/yum.repos.d/mongodb-org-6.0.repo
  3. [mongodb-org-6.0]
  4. name=MongoDB Repository
  5. baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/6.0/x86_64/
  6. gpgcheck=1
  7. enabled=1
  8. gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
  9. [root@MongoDB-Master ~]# yum install -y mongodb-org
  10. =========================================================================================================
  11. # 如要安装特定版本的 MongoDB,请单独指定每个组件包并将版本号附加到包名称,例如
  12. 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
  13. # yum当更新版本可用时升级软件包。为防止意外升级,请固定包。要固定包,请将以下exclude指令添加到您的/etc/yum.conf文件中
  14. exclude=mongodb-org,mongodb-org-database,mongodb-org-server,mongodb-mongosh,mongodb-org-mongos,mongodb-org-tools
  15. =========================================================================================================
  16. # 查看安装版本
  17. [root@MongoDB-Master ~]# mongod --version
  18. db version v6.0.11
  19. Build Info: {
  20.     "version": "6.0.11",
  21.     "gitVersion": "f797f841eaf1759c770271ae00c88b92b2766eed",
  22.     "openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
  23.     "modules": [],
  24.     "allocator": "tcmalloc",
  25.     "environment": {
  26.         "distmod": "rhel70",
  27.         "distarch": "x86_64",
  28.         "target_arch": "x86_64"
  29.     }
  30. }
  31. # 修改配置文件 (bindIp: 127.0.0.1,172.16.70.181)
  32. [root@MongoDB-Master ~]# grep -Ev "^$" /etc/mongod.conf
  33. # mongod.conf
  34. # for documentation of all options, see:
  35. #   http://docs.mongodb.org/manual/reference/configuration-options/
  36. # where to write logging data.
  37. systemLog:
  38.   destination: file
  39.   logAppend: true
  40.   path: /var/log/mongodb/mongod.log
  41. # Where and how to store data.
  42. storage:
  43.   dbPath: /var/lib/mongo
  44.   journal:
  45.     enabled: true
  46. #  engine:
  47. #  wiredTiger:
  48. # how the process runs
  49. processManagement:
  50.   timeZoneInfo: /usr/share/zoneinfo
  51. # network interfaces
  52. net:
  53.   port: 27017
  54.   # 注意:本机的ip地址。否则后面进行副本集初始化的时候可能会失败!
  55.   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.
  56. #security:
  57. #operationProfiling:
  58. replication:
  59.    # 定义副本集名称
  60.    replSetName: testrs0
  61. #sharding:
  62. ## Enterprise-Only Options
  63. #auditLog:
  64. #snmp:
  65. # 确保运行MongoDB的用户有权访问相关目录
  66. [root@MongoDB-Master ~]# grep mongo /etc/passwd
  67. mongod:x:997:996:mongod:/var/lib/mongo:/bin/false
  68. [root@MongoDB-Master ~]# ls -ld /var/log/mongodb/mongod.log /var/lib/mongo
  69. drwxr-xr-x 4 mongod mongod   4096 Oct 20 10:25 /var/lib/mongo
  70. -rw-r----- 1 mongod mongod 171974 Oct 20 10:22 /var/log/mongodb/mongod.log
  71. # 启动MongoDB
  72. [root@MongoDB-Master ~]# systemctl start mongod && systemctl enable mongod
  73. [root@MongoDB-Master ~]# systemctl list-units | grep mongod
  74. mongod.service                                  loaded active running   MongoDB Database Server
  75. [root@MongoDB-Master ~]# ps axu | grep mongod
  76. mongod     1563  1.8  2.4 2805700 97536 ?       Ssl  11:26   0:01 /usr/bin/mongod -f /etc/mongod.conf
  77. root       1703  0.0  0.0 112808   968 pts/0    S+   11:27   0:00 grep --color=auto mongod
  78. [root@MongoDB-Master ~]# netstat -ntpl | grep mongod
  79. tcp        0      0 172.16.70.181:27017     0.0.0.0:*               LISTEN      1563/mongod
  80. tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      1563/mongod
  81. [root@MongoDB-Master ~]# ls -l /tmp/mongodb-27017.sock
  82. srwx------ 1 mongod mongod 0 Oct 20 11:26 /tmp/mongodb-27017.sock
复制代码
部署副本集

这里的_id与配置文件mongod.conf中replSetName保持一致。
  1. # 在任意节点执行 rs.initiate,这里选择在MongoDB-Master操作初始化。
  2. [root@MongoDB-Master ~]# mongosh
  3. test> rs.initiate( {
  4. ...    _id : "testrs0",
  5. ...    members: [
  6. ...       { _id: 0, host: "172.16.70.181:27017" },
  7. ...       { _id: 1, host: "172.16.70.182:27017" },
  8. ...       { _id: 2, host: "172.16.70.183:27017" }
  9. ...    ]
  10. ... })
  11. { ok: 1 }
  12. # 查看副本集配置,确保只有一个主节点
  13. testrs0 [direct: primary] test> rs.conf()
  14. {
  15.   _id: 'testrs0',
  16.   version: 1,
  17.   term: 1,
  18.   members: [
  19.     {
  20.       _id: 0,
  21.       host: '172.16.70.181:27017',
  22.       arbiterOnly: false,   # 是否为仲裁者,默认为false
  23.       buildIndexes: true,   # 是否为构建索引成员
  24.       hidden: false,        # 是否为隐藏成员
  25.       priority: 1,          # 范围0~1000,默认为1,值大为主节点primary,值为0则不能成为primay(仲裁)
  26.       tags: {},
  27.       secondaryDelaySecs: Long("0"),   # 从节点复制延迟时间,单位秒s
  28.       votes: 1                         # 选举投票的数量
  29.     },
  30.     {
  31.       _id: 1,
  32.       host: '172.16.70.182:27017',
  33.       arbiterOnly: false,
  34.       buildIndexes: true,
  35.       hidden: false,
  36.       priority: 1,           # 默认为1
  37.       tags: {},
  38.       secondaryDelaySecs: Long("0"),
  39.       votes: 1
  40.     },
  41.     {
  42.       _id: 2,
  43.       host: '172.16.70.183:27017',
  44.       arbiterOnly: false,
  45.       buildIndexes: true,
  46.       hidden: false,
  47.       priority: 1,        # 默认为1
  48.       tags: {},
  49.       secondaryDelaySecs: Long("0"),
  50.       votes: 1
  51.     }
  52.   ],
  53.   protocolVersion: Long("1"),
  54.   writeConcernMajorityJournalDefault: true,
  55.   settings: {
  56.     chainingAllowed: true,
  57.     heartbeatIntervalMillis: 2000,
  58.     heartbeatTimeoutSecs: 10,
  59.     electionTimeoutMillis: 10000,
  60.     catchUpTimeoutMillis: -1,
  61.     catchUpTakeoverDelayMillis: 30000,
  62.     getLastErrorModes: {},
  63.     getLastErrorDefaults: { w: 1, wtimeout: 0 },
  64.     replicaSetId: ObjectId("6531f7207c8f661d6f787810")
  65.   }
  66. }
  67. testrs0 [direct: primary] test> rs.status()
  68. {
  69.   set: 'testrs0',                              # 副本集名称
  70.   date: ISODate("2023-10-20T04:06:56.352Z"),   # 当前时间
  71.   myState: 1,                                  # 成员的副本状态(0~10);常见 1:PRIMARY,2:SECONDARY,7:ARBITER,8:DOWN
  72.   term: Long("2"),                             # 获得选举的票数
  73.   syncSourceHost: '',                          # 实例同步成员的主机名
  74.   syncSourceId: -1,                            # 实例同成员名称
  75.   heartbeatIntervalMillis: Long("2000"),       # 心跳频率,毫秒ms
  76.   majorityVoteCount: 2,                        # 被选举为主节点所需要的票数
  77.   writeMajorityCount: 2,                       # 满足写操作所需要的票数
  78.   votingMembersCount: 3,                       # 该副本集中成员数量
  79.   writableVotingMembersCount: 3,               # 有投票权的成员数量
  80.   optimes: {
  81.     lastCommittedOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  82.     lastCommittedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
  83.     readConcernMajorityOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  84.     appliedOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  85.     durableOpTime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  86.     lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
  87.     lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z")
  88.   },
  89.   lastStableRecoveryTimestamp: Timestamp({ t: 1697774793, i: 1 }),
  90.   electionCandidateMetrics: {
  91.     lastElectionReason: 'stepUpRequestSkipDryRun',
  92.     lastElectionDate: ISODate("2023-10-20T04:04:37.304Z"),
  93.     electionTerm: Long("2"),
  94.     lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1697774676, i: 1 }), t: Long("1") },
  95.     lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1697774676, i: 1 }), t: Long("1") },
  96.     numVotesNeeded: 2,
  97.     priorityAtElection: 1,
  98.     electionTimeoutMillis: Long("10000"),
  99.     priorPrimaryMemberId: 1,
  100.     numCatchUpOps: Long("0"),
  101.     newTermStartDate: ISODate("2023-10-20T04:04:37.311Z"),
  102.     wMajorityWriteAvailabilityDate: ISODate("2023-10-20T04:04:38.331Z")
  103.   },
  104.   electionParticipantMetrics: {
  105.     votedForCandidate: true,
  106.     electionTerm: Long("1"),
  107.     lastVoteDate: ISODate("2023-10-20T03:42:36.120Z"),
  108.     electionCandidateMemberId: 1,
  109.     voteReason: '',
  110.     lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1697773344, i: 1 }), t: Long("-1") },
  111.     maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1697773344, i: 1 }), t: Long("-1") },
  112.     priorityAtElection: 1
  113.   },
  114.   members: [
  115.     {
  116.       _id: 0,                          # 副本集中节点编号
  117.       name: '172.16.70.181:27017',     # 服务器名称及端口号
  118.       health: 1,                       # 健康状态;1为正常,0为异常
  119.       state: 1,                        # 当前状态;数值小为primary,数值大为secondary
  120.       stateStr: 'PRIMARY',             # 主节点(PRIMARY),从节点(SECONDARY)
  121.       uptime: 2424,                    # 在线时间(秒)
  122.       optime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },    # 最后一次应用日志(oplog)信息
  123.       optimeDate: ISODate("2023-10-20T04:06:47.000Z"),                     # 最后一次应用日志(oplog)时间
  124.       lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"),            # 该成员在主节点上应用的最后一次操作的时间
  125.       lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z"),            # 最后一次写入成员日志的操作首次在主节点上应用时的时间
  126.       syncSourceHost: '',
  127.       syncSourceId: -1,
  128.       infoMessage: '',
  129.       electionTime: Timestamp({ t: 1697774677, i: 1 }),                    # primary从操作日志选举时间戳信息
  130.       electionDate: ISODate("2023-10-20T04:04:37.000Z"),                   # 被选定为primary的时间
  131.       configVersion: 1,                                                    # 副本集版本
  132.       configTerm: 2,
  133.       self: true,
  134.       lastHeartbeatMessage: ''
  135.     },
  136.     {
  137.       _id: 1,
  138.       name: '172.16.70.182:27017',
  139.       health: 1,            
  140.       state: 2,               # 数值小为primary,数值大为secondary
  141.       stateStr: 'SECONDARY',  # 从节点
  142.       uptime: 84,
  143.       optime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  144.       optimeDurable: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  145.       optimeDate: ISODate("2023-10-20T04:06:47.000Z"),
  146.       optimeDurableDate: ISODate("2023-10-20T04:06:47.000Z"),
  147.       lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
  148.       lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z"),
  149.       lastHeartbeat: ISODate("2023-10-20T04:06:55.647Z"),
  150.       lastHeartbeatRecv: ISODate("2023-10-20T04:06:55.575Z"),
  151.       pingMs: Long("0"),
  152.       lastHeartbeatMessage: '',
  153.       syncSourceHost: '172.16.70.183:27017',
  154.       syncSourceId: 2,
  155.       infoMessage: '',
  156.       configVersion: 1,
  157.       configTerm: 2
  158.     },
  159.     {
  160.       _id: 2,
  161.       name: '172.16.70.183:27017',
  162.       health: 1,              
  163.       state: 2,               # 数值小为primary,数值大为secondary
  164.       stateStr: 'SECONDARY',  # 从节点
  165.       uptime: 1471,
  166.       optime: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  167.       optimeDurable: { ts: Timestamp({ t: 1697774807, i: 1 }), t: Long("2") },
  168.       optimeDate: ISODate("2023-10-20T04:06:47.000Z"),
  169.       optimeDurableDate: ISODate("2023-10-20T04:06:47.000Z"),
  170.       lastAppliedWallTime: ISODate("2023-10-20T04:06:47.335Z"),
  171.       lastDurableWallTime: ISODate("2023-10-20T04:06:47.335Z"),
  172.       lastHeartbeat: ISODate("2023-10-20T04:06:55.561Z"),
  173.       lastHeartbeatRecv: ISODate("2023-10-20T04:06:54.598Z"),
  174.       pingMs: Long("0"),
  175.       lastHeartbeatMessage: '',
  176.       syncSourceHost: '172.16.70.181:27017',
  177.       syncSourceId: 0,
  178.       infoMessage: '',
  179.       configVersion: 1,
  180.       configTerm: 2
  181.     }
  182.   ],
  183.   ok: 1,
  184.   '$clusterTime': {
  185.     clusterTime: Timestamp({ t: 1697774807, i: 1 }),
  186.     signature: {
  187.       hash: Binary.createFromBase64("AAAAAAAAAAAAAAAAAAAAAAAAAAA=", 0),
  188.       keyId: Long("0")
  189.     }
  190.   },
  191.   operationTime: Timestamp({ t: 1697774807, i: 1 })
  192. }
  193. testrs0 [direct: primary] test>
复制代码

复制功能测试
  1. # 在主节点(172.16.70.181)上新增mydb库,并创建myColl文档
  2. [root@MongoDB-Master ~]# mongosh
  3. testrs0 [direct: primary] test>
  4. testrs0 [direct: primary] test> show dbs
  5. admin    80.00 KiB
  6. config  208.00 KiB
  7. local   484.00 KiB
  8. testrs0 [direct: primary] test> use mydb
  9. switched to db mydb
  10. testrs0 [direct: primary] mydb> db.myColl.insertOne({ name: "zhang" })
  11. {
  12.   acknowledged: true,
  13.   insertedId: ObjectId("65361759be7d5c1abe9d83ee")
  14. }
  15. testrs0 [direct: primary] mydb> db.myColl.find()
  16. [ { _id: ObjectId("65361759be7d5c1abe9d83ee"), name: 'zhang' } ]
  17. # 在从节点(172.16.70.182/183)上查看复制同步数据结果
  18. [root@MongoDB-Slave01 ~]# mongosh
  19. testrs0 [direct: secondary] test> use mydb
  20. switched to db mydb
  21. testrs0 [direct: secondary] mydb> show collections
  22. myColl
  23. testrs0 [direct: secondary] mydb> db.myColl.find()
  24. MongoServerError: not primary and secondaryOk=false - consider using db.getMongo().setReadPref() or readPreference in the connection string
  25. # MongoServerError 报错!
  26. # 这是因为mongodb默认是从主节点读写数据的,副本节点上不允许读,需要设置副本节点可以读
  27. testrs0 [direct: secondary] mydb> db.getMongo().setReadPref('secondary')
  28. testrs0 [direct: secondary] mydb> db.myColl.find()
  29. [ { _id: ObjectId("65361759be7d5c1abe9d83ee"), name: 'zhang' } ]
  30. # 此时,主节点数据已经同步到从节点上
复制代码
故障转移功能测试
  1. # 假设主节点(172.16.70.181)故障
  2. [root@MongoDB-Master ~]# systemctl stop mongod
  3. [root@MongoDB-Master ~]# netstat -ntpl | grep mongod
  4. # 登录从节点查看副本集状态
  5. [root@MongoDB-Slave01 ~]# mongosh
  6. testrs0 [direct: primary] test> rs.status()
  7. {
  8.   set: 'testrs0',
  9.   date: ISODate("2023-10-23T07:55:53.369Z"),
  10.   myState: 1,
  11.   term: Long("2"),
  12.   syncSourceHost: '',
  13.   syncSourceId: -1,
  14.   heartbeatIntervalMillis: Long("2000"),
  15.   majorityVoteCount: 2,
  16.   writeMajorityCount: 2,
  17.   votingMembersCount: 3,
  18.   writableVotingMembersCount: 3,
  19.   optimes: {
  20.     lastCommittedOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
  21.     lastCommittedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
  22.     readConcernMajorityOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
  23.     appliedOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
  24.     durableOpTime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
  25.     lastAppliedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
  26.     lastDurableWallTime: ISODate("2023-10-23T07:55:43.519Z")
  27.   },
  28.   lastStableRecoveryTimestamp: Timestamp({ t: 1698047693, i: 1 }),
  29.   electionCandidateMetrics: {
  30.     lastElectionReason: 'stepUpRequestSkipDryRun',
  31.     lastElectionDate: ISODate("2023-10-23T07:51:13.449Z"),
  32.     electionTerm: Long("2"),
  33.     lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1698047468, i: 1 }), t: Long("1") },
  34.     lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1698047468, i: 1 }), t: Long("1") },
  35.     numVotesNeeded: 2,
  36.     priorityAtElection: 1,
  37.     electionTimeoutMillis: Long("10000"),
  38.     priorPrimaryMemberId: 0,
  39.     numCatchUpOps: Long("0"),
  40.     newTermStartDate: ISODate("2023-10-23T07:51:13.456Z"),
  41.     wMajorityWriteAvailabilityDate: ISODate("2023-10-23T07:51:14.459Z")
  42.   },
  43.   electionParticipantMetrics: {
  44.     votedForCandidate: true,
  45.     electionTerm: Long("1"),
  46.     lastVoteDate: ISODate("2023-10-23T07:47:58.216Z"),
  47.     electionCandidateMemberId: 0,
  48.     voteReason: '',
  49.     lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1698047267, i: 1 }), t: Long("-1") },
  50.     maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1698047267, i: 1 }), t: Long("-1") },
  51.     priorityAtElection: 1
  52.   },
  53.   members: [
  54.     {
  55.       _id: 0,
  56.       name: '172.16.70.181:27017',
  57.       health: 0,
  58.       state: 8,
  59.       stateStr: '(not reachable/healthy)',
  60.       uptime: 0,
  61.       optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
  62.       optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
  63.       optimeDate: ISODate("1970-01-01T00:00:00.000Z"),
  64.       optimeDurableDate: ISODate("1970-01-01T00:00:00.000Z"),
  65.       lastAppliedWallTime: ISODate("2023-10-23T07:51:14.906Z"),
  66.       lastDurableWallTime: ISODate("2023-10-23T07:51:14.906Z"),
  67.       lastHeartbeat: ISODate("2023-10-23T07:55:52.462Z"),
  68.       lastHeartbeatRecv: ISODate("2023-10-23T07:51:28.493Z"),
  69.       pingMs: Long("0"),
  70.       lastHeartbeatMessage: 'Error connecting to 172.16.70.181:27017 :: caused by :: Connection refused',     # 提示: Error
  71.       syncSourceHost: '',
  72.       syncSourceId: -1,
  73.       infoMessage: '',
  74.       configVersion: 1,
  75.       configTerm: 2
  76.     },
  77.     {
  78.       _id: 1,
  79.       name: '172.16.70.182:27017',
  80.       health: 1,
  81.       state: 1,
  82.       stateStr: 'PRIMARY',
  83.       uptime: 1005,
  84.       optime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
  85.       optimeDate: ISODate("2023-10-23T07:55:43.000Z"),
  86.       lastAppliedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
  87.       lastDurableWallTime: ISODate("2023-10-23T07:55:43.519Z"),
  88.       syncSourceHost: '',
  89.       syncSourceId: -1,
  90.       infoMessage: '',
  91.       electionTime: Timestamp({ t: 1698047473, i: 1 }),
  92.       electionDate: ISODate("2023-10-23T07:51:13.000Z"),
  93.       configVersion: 1,
  94.       configTerm: 2,
  95.       self: true,
  96.       lastHeartbeatMessage: ''
  97.     },
  98.     {
  99.       _id: 2,
  100.       name: '172.16.70.183:27017',
  101.       health: 1,
  102.       state: 2,
  103.       stateStr: 'SECONDARY',
  104.       uptime: 486,
  105.       optime: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
  106.       optimeDurable: { ts: Timestamp({ t: 1698047743, i: 1 }), t: Long("2") },
  107.       optimeDate: ISODate("2023-10-23T07:55:43.000Z"),
  108.       optimeDurableDate: ISODate("2023-10-23T07:55:43.000Z"),
  109.       lastAppliedWallTime: ISODate("2023-10-23T07:55:43.519Z"),
  110.       lastDurableWallTime: ISODate("2023-10-23T07:55:43.519Z"),
  111.       lastHeartbeat: ISODate("2023-10-23T07:55:52.043Z"),
  112.       lastHeartbeatRecv: ISODate("2023-10-23T07:55:52.568Z"),
  113.       pingMs: Long("0"),
  114.       lastHeartbeatMessage: '',
  115.       syncSourceHost: '172.16.70.182:27017',
  116.       syncSourceId: 1,
  117.       infoMessage: '',
  118.       configVersion: 1,
  119.       configTerm: 2
  120.     }
  121.   ],
  122.   ok: 1,
  123.   '$clusterTime': {
  124.     clusterTime: Timestamp({ t: 1698047743, i: 1 }),
  125.     signature: {
  126.       hash: Binary.createFromBase64("AAAAAAAAAAAAAAAAAAAAAAAAAAA=", 0),
  127.       keyId: Long("0")
  128.     }
  129.   },
  130.   operationTime: Timestamp({ t: 1698047743, i: 1 })
  131. }
  132. testrs0 [direct: primary] test>
  133. # 此次,从节点(172.16.70.182)经过选举后,成为新的主节点。
  134. # 原主节点(172.16.70.181)故障恢复后,将成为新的主节点(172.16.70.182)的从节点。
  135. # 如果想实例预设成为主节点,可设置更高优先级priority(默认优先级为1,m值是0~1000之间的数字,数字越大优先级越高,m=0,则此节点永远不能成为主节点)
  136. # 即先移除rs.remove("ip:port"),再新增rs.add( { host: "ip:port", priority: Num } )
复制代码
更改副本集优先级
  1. # 查看当前副本集配置
  2. rs.conf()
  3. # n为 _id 值,从0开始为第一个节点,1为第二个节点,....
  4. # 默认优先级为1,m值是0~1000之间的数字,数字越大优先级越高,m=0,则此节点永远不能成为主节点(仲裁)
  5. cfg.members[n].priority = m
  6. # 重新配置当前副本集
  7. rs.reconfig(cfg)
复制代码
新增副本集成员
  1. # 必须在主节点上操作
  2. # 新增具有默认投票和优先级的成员到副本集
  3. rs.add( { host: "mongodbd4.example.net:27017" } )
  4. rs.add( "mongodbd4.example.net:27017" )
  5. # 新增优先级0的成员到副本集
  6. rs.add( { host: "mongodbd4.example.net:27017", priority: 0 } )
  7. # 新增仲裁者成员到副本集
  8. rs.add( { host: "mongodb3.example.net:27017", arbiterOnly: true } )
  9. rs.add("mongodb3.example.net:27017", true)
复制代码
删除副本成员
  1. rs.remove("mongod3.example.net:27017")
  2. rs.remove("mongod3.example.net")
复制代码
替换副本集成员
  1. cfg = rs.conf()
  2. cfg.members[0].host = "mongo2.example.net"
  3. rs.reconfig(cfg)
复制代码
            作者:上古南城
            出处:https://www.cnblogs.com/zhangwencheng
            版权:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出             原文链接
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

反转基因福娃

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表