news 2026/5/1 18:03:55

mongodb Replica Set集群搭建(三节点)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
mongodb Replica Set集群搭建(三节点)

mongodb Replica Set集群搭建(三节点)

节点IP分配

192.168.56.107
192.168.56.113
192.168.56.114

准备软件包(所有节点)

创建目录 (所有节点)

准备配置文件

192.168.56.107

storage: dbPath: "D:\\mongodb-win32-x86_64-windows-7.0.4\\data" systemLog: destination: "file" path: "D:\\mongodb-win32-x86_64-windows-7.0.4\\logs\\mongodb.log" net: bindIp: 192.168.56.107 port: 27017 maxIncomingConnections: 10000 replication: replSetName: rs0

192.168.56.113

storage: dbPath: "D:\\mongodb-win32-x86_64-windows-7.0.4\\data" systemLog: destination: "file" path: "D:\\mongodb-win32-x86_64-windows-7.0.4\\logs\\mongodb.log" net: bindIp: 192.168.56.114 port: 27016 maxIncomingConnections: 10000 replication: replSetName: rs0

192.168.56.114

storage: dbPath: "D:\\mongodb-win32-x86_64-windows-7.0.4\\data" systemLog: destination: "file" path: "D:\\mongodb-win32-x86_64-windows-7.0.4\\logs\\mongodb.log" net: bindIp: 192.168.56.113 port: 27013 maxIncomingConnections: 10000 replication: replSetName: rs0

启动三个节点

mongod --config "D:\mongodb-win32-x86_64-windows-7.0.4\conf\mongodb.cfg" --serviceName MongoDB --serviceDisplayName MongoDB --install net start MongoDB

连接任意一台数据库

D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.107:27017" Current Mongosh Log ID: 698b3a9a5f20a9775c628c9f Connecting to: mongodb://192.168.56.107:27017/?directConnection=true&appName=mongosh+2.6.0 Using MongoDB: 7.0.4 Using Mongosh: 2.6.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ------ The server generated these startup warnings when booting 2026-02-10T16:32:27.150+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ test>

初始化集群

cfg={_id:“rs0”, members: [ {_id:0,host:‘192.168.56.107:27017’,priority:2} ,{_id:1,host:‘192.168.56.113:27013’,priority:1} ,{_id:2,host:‘192.168.56.114:27016’,arbiterOnly:true}]};

rs.initiate(cfg)

rs.status();

说明:
host:指定的是节点的ip地址与端口号

priority:指的是权重,权重最高的是主节点 ,权重大小的判定(数字最大>数字小的>没有写权重属性的)

arbiterOnly:代表是否作为仲裁节点

D :\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.107:27017" Current Mongosh Log ID: 698b3a9a5f20a9775c628c9f Connecting to: mongodb://192.168.56.107:27017/?directConnection=true&appName=mongosh+2.6.0 Using MongoDB: 7.0.4 Using Mongosh: 2.6.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ------ The server generated these startup warnings when booting 2026-02-10T16:32:27.150+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ test> cfg={_id:"rs0", members: [ {_id:0,host:'192.168.56.107:27017',priority:2} ,{_id:1,host:'192.168.56.113:27013',priority:1} ,{_id:2,host:'192.168.56.114:27016',arbiterOnly:true}]}; { _id: 'rs0', members: [ { _id: 0, host: '192.168.56.107:27017', priority: 2 }, { _id: 1, host: '192.168.56.113:27013', priority: 1 }, { _id: 2, host: '192.168.56.114:27016', arbiterOnly: true } ] } test> test> rs.initiate(cfg) { ok: 1 } rs0 [direct: secondary] test> rs0 [direct: secondary] test> rs.status(); { set: 'rs0', date: ISODate('2026-02-10T14:04:10.888Z'), myState: 1, term: Long('1'), syncSourceHost: '', syncSourceId: -1, heartbeatIntervalMillis: Long('2000'), majorityVoteCount: 2, writeMajorityCount: 2, votingMembersCount: 3, writableVotingMembersCount: 2, optimes: { lastCommittedOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') }, lastCommittedWallTime: ISODate('2026-02-10T14:04:03.194Z'), readConcernMajorityOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') }, appliedOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') }, durableOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') }, lastAppliedWallTime: ISODate('2026-02-10T14:04:03.194Z'), lastDurableWallTime: ISODate('2026-02-10T14:04:03.194Z') }, lastStableRecoveryTimestamp: Timestamp({ t: 1770732230, i: 1 }), electionCandidateMetrics: { lastElectionReason: 'electionTimeout', lastElectionDate: ISODate('2026-02-10T14:04:02.338Z'), electionTerm: Long('1'), lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') }, lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') }, numVotesNeeded: 2, priorityAtElection: 2, electionTimeoutMillis: Long('10000'), numCatchUpOps: Long('0'), newTermStartDate: ISODate('2026-02-10T14:04:02.475Z'), wMajorityWriteAvailabilityDate: ISODate('2026-02-10T14:04:02.988Z') }, members: [ { _id: 0, name: '192.168.56.107:27017', health: 1, state: 1, stateStr: 'PRIMARY', uptime: 19906, optime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') }, optimeDate: ISODate('2026-02-10T14:04:03.000Z'), lastAppliedWallTime: ISODate('2026-02-10T14:04:03.194Z'), lastDurableWallTime: ISODate('2026-02-10T14:04:03.194Z'), syncSourceHost: '', syncSourceId: -1, infoMessage: 'Could not find member to sync from', electionTime: Timestamp({ t: 1770732242, i: 1 }), electionDate: ISODate('2026-02-10T14:04:02.000Z'), configVersion: 1, configTerm: 1, self: true, lastHeartbeatMessage: '' }, { _id: 1, name: '192.168.56.113:27013', health: 1, state: 2, stateStr: 'SECONDARY', uptime: 20, optime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') }, optimeDurable: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') }, optimeDate: ISODate('2026-02-10T14:04:03.000Z'), optimeDurableDate: ISODate('2026-02-10T14:04:03.000Z'), lastAppliedWallTime: ISODate('2026-02-10T14:04:03.194Z'), lastDurableWallTime: ISODate('2026-02-10T14:04:03.194Z'), lastHeartbeat: ISODate('2026-02-10T14:04:10.452Z'), lastHeartbeatRecv: ISODate('2026-02-10T14:04:09.409Z'), pingMs: Long('0'), lastHeartbeatMessage: '', syncSourceHost: '192.168.56.107:27017', syncSourceId: 0, infoMessage: '', configVersion: 1, configTerm: 1 }, { _id: 2, name: '192.168.56.114:27016', health: 1, state: 7, stateStr: 'ARBITER', uptime: 20, lastHeartbeat: ISODate('2026-02-10T14:04:10.452Z'), lastHeartbeatRecv: ISODate('2026-02-10T14:04:10.417Z'), pingMs: Long('0'), lastHeartbeatMessage: '', syncSourceHost: '', syncSourceId: -1, infoMessage: '', configVersion: 1, configTerm: 1 } ], ok: 1, '$clusterTime': { clusterTime: Timestamp({ t: 1770732243, i: 7 }), signature: { hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0), keyId: Long('0') } }, operationTime: Timestamp({ t: 1770732243, i: 7 }) } rs0 [direct: primary] test>

测试登录主从

mongosh “mongodb://192.168.56.107:27017”

D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.107:27017" Current Mongosh Log ID: 698b3d37a4ce9a857e628c9f Connecting to: mongodb://192.168.56.107:27017/?directConnection=true&appName=mongosh+2.6.0 Using MongoDB: 7.0.4 Using Mongosh: 2.6.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ------ The server generated these startup warnings when booting 2026-02-10T16:32:27.150+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ rs0 [direct: primary] test> exit

mongosh “mongodb://192.168.56.113:27013”

D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.113:27013" Current Mongosh Log ID: 698b49fdf5a5d6f930628c9f Connecting to: mongodb://192.168.56.113:27013/?directConnection=true&appName=mongosh+2.6.0 Using MongoDB: 7.0.4 Using Mongosh: 2.6.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ------ The server generated these startup warnings when booting 2026-02-10T16:29:31.285+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ rs0 [direct: secondary] test> exit

mongosh “mongodb://192.168.56.114:27016”

D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.114:27016" Current Mongosh Log ID: 698b4a0a3aa7c61154628c9f Connecting to: mongodb://192.168.56.114:27016/?directConnection=true&appName=mongosh+2.6.0 Using MongoDB: 7.0.4 Using Mongosh: 2.6.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ------ The server generated these startup warnings when booting 2026-02-10T16:29:26.854+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted 2026-02-10T22:03:51.238+08:00: ** WARNING: Arbiters are not supported in quarterly binary versions ------ rs0 [direct: arbiter] test>

查看节点配置

rs0 [direct: arbiter] test> rs.conf() { _id: 'rs0', version: 1, term: 1, members: [ { _id: 0, host: '192.168.56.107:27017', arbiterOnly: false, buildIndexes: true, hidden: false, priority: 2, tags: {}, secondaryDelaySecs: Long('0'), votes: 1 }, { _id: 1, host: '192.168.56.113:27013', arbiterOnly: false, buildIndexes: true, hidden: false, priority: 1, tags: {}, secondaryDelaySecs: Long('0'), votes: 1 }, { _id: 2, host: '192.168.56.114:27016', arbiterOnly: true, buildIndexes: true, hidden: false, priority: 0, 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('698b3ac636c0e40ea3e5f66c') } } rs0 [direct: arbiter] test>

##查看节点的状态

rs0 [direct: arbiter] test> rs.status() { set: 'rs0', date: ISODate('2026-02-10T15:14:28.395Z'), myState: 7, term: Long('1'), syncSourceHost: '', syncSourceId: -1, heartbeatIntervalMillis: Long('2000'), majorityVoteCount: 2, writeMajorityCount: 2, votingMembersCount: 3, writableVotingMembersCount: 2, optimes: { lastCommittedOpTime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') }, lastCommittedWallTime: ISODate('2026-02-10T15:14:24.033Z'), readConcernMajorityOpTime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') }, appliedOpTime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') }, durableOpTime: { ts: Timestamp({ t: 0, i: 0 }), t: Long('-1') }, lastAppliedWallTime: ISODate('2026-02-10T15:14:24.033Z'), lastDurableWallTime: ISODate('1970-01-01T00:00:00.000Z') }, lastStableRecoveryTimestamp: Timestamp({ t: 0, i: 0 }), electionParticipantMetrics: { votedForCandidate: true, electionTerm: Long('1'), lastVoteDate: ISODate('2026-02-10T14:04:02.340Z'), electionCandidateMemberId: 0, voteReason: '', lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') }, maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') }, priorityAtElection: 0 }, members: [ { _id: 0, name: '192.168.56.107:27017', health: 1, state: 1, stateStr: 'PRIMARY', uptime: 4237, optime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') }, optimeDurable: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') }, optimeDate: ISODate('2026-02-10T15:14:24.000Z'), optimeDurableDate: ISODate('2026-02-10T15:14:24.000Z'), lastAppliedWallTime: ISODate('2026-02-10T15:14:24.033Z'), lastDurableWallTime: ISODate('2026-02-10T15:14:24.033Z'), lastHeartbeat: ISODate('2026-02-10T15:14:27.304Z'), lastHeartbeatRecv: ISODate('2026-02-10T15:14:27.940Z'), pingMs: Long('0'), lastHeartbeatMessage: '', syncSourceHost: '', syncSourceId: -1, infoMessage: '', electionTime: Timestamp({ t: 1770732242, i: 1 }), electionDate: ISODate('2026-02-10T14:04:02.000Z'), configVersion: 1, configTerm: 1 }, { _id: 1, name: '192.168.56.113:27013', health: 1, state: 2, stateStr: 'SECONDARY', uptime: 4237, optime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') }, optimeDurable: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') }, optimeDate: ISODate('2026-02-10T15:14:24.000Z'), optimeDurableDate: ISODate('2026-02-10T15:14:24.000Z'), lastAppliedWallTime: ISODate('2026-02-10T15:14:24.033Z'), lastDurableWallTime: ISODate('2026-02-10T15:14:24.033Z'), lastHeartbeat: ISODate('2026-02-10T15:14:26.690Z'), lastHeartbeatRecv: ISODate('2026-02-10T15:14:27.624Z'), pingMs: Long('0'), lastHeartbeatMessage: '', syncSourceHost: '192.168.56.107:27017', syncSourceId: 0, infoMessage: '', configVersion: 1, configTerm: 1 }, { _id: 2, name: '192.168.56.114:27016', health: 1, state: 7, stateStr: 'ARBITER', uptime: 24304, syncSourceHost: '', syncSourceId: -1, infoMessage: '', configVersion: 1, configTerm: 1, self: true, lastHeartbeatMessage: '' } ], ok: 1 } rs0 [direct: arbiter] test>

确认同步情况

rs.printSecondaryReplicationInfo()

D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.113:27013" Current Mongosh Log ID: 698b4c9ea7994c5d08628c9f Connecting to: mongodb://192.168.56.113:27013/?directConnection=true&appName=mongosh+2.6.0 Using MongoDB: 7.0.4 Using Mongosh: 2.6.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ------ The server generated these startup warnings when booting 2026-02-10T16:29:31.285+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ rs0 [direct: secondary] test> rs.printSecondaryReplicationInfo() source: 192.168.56.113:27013 { syncedTo: 'Tue Feb 10 2026 23:22:41 GMT+0800 (中国标准时间)', replLag: '0 secs (0 hrs) behind the primary ' } rs0 [direct: secondary] test>

查看集群组成员

rs.conf().members

通过 rs.status() 查看当前副本集状态,找到members需要切换为Primary节点的数组下标,cfg.members[0] 中的 [0] 就是数组索引,表示第 1 个成员

rs0 [direct: primary] test> rs.conf().members [ { _id: 0, host: '192.168.56.107:27017', arbiterOnly: false, buildIndexes: true, hidden: false, priority: 2, tags: {}, secondaryDelaySecs: Long('0'), votes: 1 }, { _id: 1, host: '192.168.56.113:27013', arbiterOnly: false, buildIndexes: true, hidden: false, priority: 1, tags: {}, secondaryDelaySecs: Long('0'), votes: 1 }, { _id: 2, host: '192.168.56.114:27016', arbiterOnly: true, buildIndexes: true, hidden: false, priority: 0, tags: {}, secondaryDelaySecs: Long('0'), votes: 1 } ]

主从切换测试

在主节点执行
config = rs.conf()
config.members[1].priority = 5
rs.reconfig(config)

说明:
priority有效范围是 0–1000 的浮点数(含 0 和 1000),默认值 1。
mongodb中rs.reconfig(config)解释
底层调用的是 replSetReconfig 命令,只能在主节点上执行(除非加 {force:true})

rs0 [direct: primary] test> config = rs.conf() <<< 查看当前主从配置的priority { _id: 'rs0', version: 1, term: 3, members: [ { _id: 0, host: '192.168.56.107:27017', arbiterOnly: false, buildIndexes: true, hidden: false, priority: 2, tags: {}, secondaryDelaySecs: Long('0'), votes: 1 }, { _id: 1, host: '192.168.56.113:27013', arbiterOnly: false, buildIndexes: true, hidden: false, priority: 1, tags: {}, secondaryDelaySecs: Long('0'), votes: 1 }, { _id: 2, host: '192.168.56.114:27016', arbiterOnly: true, buildIndexes: true, hidden: false, priority: 0, 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('698b3ac636c0e40ea3e5f66c') } } rs0 [direct: primary] test> config.members[1].priority = 5 <<<<< 修改从库的priority节点大于当前主节点的priority 5 rs0 [direct: primary] test> rs.reconfig(config) <<<<< 刷新配置信息 { ok: 1, '$clusterTime': { clusterTime: Timestamp({ t: 1770737382, i: 1 }), signature: { hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0), keyId: Long('0') } }, operationTime: Timestamp({ t: 1770737382, i: 1 }) } rs0 [direct: primary] test> rs0 [direct: secondary] test> <<<<<<<<< 再次刷新原来的主库变成了从库 rs0 [direct: secondary] test>

原来的从库变成了主库

D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.113:27013" Current Mongosh Log ID: 698b4f9be31ca9da01628c9f Connecting to: mongodb://192.168.56.113:27013/?directConnection=true&appName=mongosh+2.6.0 Using MongoDB: 7.0.4 Using Mongosh: 2.6.0 For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/ ------ The server generated these startup warnings when booting 2026-02-10T16:29:31.285+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted ------ rs0 [direct: primary] test>
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/25 10:29:34

75 CyclicBarrier循环屏障

CyclicBarrier循环屏障 本文深入剖析CyclicBarrier循环屏障的核心原理与应用场景,详解await等待机制、reset重置操作、分阶段任务执行策略,对比CountDownLatch的区别,掌握多线程协同任务的最佳实践。 1 为什么需要CyclicBarrier? 实际业务场景 在企业级系统开发中,经常遇到需…

作者头像 李华
网站建设 2026/4/22 17:10:25

CANN shmem 共享内存通信模型的进程间同步机制

cann组织链接&#xff1a;https://atomgit.com/cann shmem仓库链接&#xff1a;https://atomgit.com/cann/shmem 前言 在多进程、多设备协同计算场景中&#xff0c;高效的进程间同步是确保数据一致性和执行正确性的关键。CANN&#xff08;Compute Architecture for Neural Net…

作者头像 李华
网站建设 2026/4/24 4:26:53

软著通:让软著申请变得简单到爆炸!

有没有遇到过这种情况&#xff1a;心血来潮做了个超炫酷的软件&#xff0c;结果却因为一堆软著材料而心情崩溃&#xff1f;“要写什么&#xff1f;要整理什么&#xff1f;这些东西哪来的排版和分页&#xff1f;”—你不是一个人&#xff0c;很多开发者都在为这事儿抓狂。软著通…

作者头像 李华
网站建设 2026/4/30 17:00:12

【YOLOv8多模态涨点改进】独家创新首发 | TGRS 2025 | 引入CGSAFusion跨模态门控注意力融合模块,通过自注意力机制 和 门控融合提升多模态信息融合,助力红外与可见光检测高效涨点

一、本文介绍 🔥本文给大家介绍使用 CGSA(Cross-Domain Gated Self-Attention)跨模态门控注意力融合模块 改进 YOLOv8 多模态目标检测 模型,可以通过自注意力机制和门控融合动态增强可见光与红外图像之间的特征交互,显著提升小目标检测能力。CGSA 通过频域信息和时域差异…

作者头像 李华
网站建设 2026/4/26 9:59:51

蜜雪冰城 小程序 sign 分析

声明: 本文章中所有内容仅供学习交流使用&#xff0c;不用于其他任何目的&#xff0c;抓包内容、敏感网址、数据接口等均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的一切后果均与作者无关&#xff01;部分python代码url "/api/v2/sho…

作者头像 李华
网站建设 2026/5/1 6:09:39

例说FPGA:可直接用于工程项目的第一手经验【3.7】

18.4 软件程序解析 1.main.c源文件软件程序解析 main.c的函数列表如表18-2所示。 表18-2 main.c文件的函数列表 2.int main(void)函数 主函数上电后稍作延时,主要是确保ADV7513芯片进入工作状态,接着给连接逻辑端hdmi_mode信号的PIO赋值,设置HDMI驱动的分辨率。代码中已经…

作者头像 李华