当前位置: 首页 > news >正文

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>
http://www.jsqmd.com/news/368997/

相关文章:

  • 2026年质量好的高压法兰/非标法兰优质供应商推荐参考 - 品牌宣传支持者
  • 2026年有实力的平焊不锈钢法兰,对焊不锈钢法兰厂家采购优选榜单 - 品牌鉴赏师
  • 转:魔搭社区每天免费提供2000次Claude Code调用
  • 2026年全过程工程咨询公司推荐:数字化转型趋势评价,涵盖城市更新与工业项目管控痛点 - 品牌推荐
  • 2026年全过程工程咨询公司推荐:权威榜单深度解析与战略选型指南 - 品牌推荐
  • 【CSDN观察】高新技术企业认定的意义在于解决三个核心矛盾
  • 【Matlab】MATLAB 图形绘制教程:hold on 保留图形用法详解(同图多曲线绘制与多组数据对比)
  • 2026靠谱的私域电商平台TOP8出炉!小鹅通等8家企业领跑行业 - 资讯焦点
  • web容器和ioc容器
  • 2026年2月访客机品牌实战报告:主流品牌产品性能及场景适配度对比 - 品牌推荐
  • 【Matlab】MATLAB 多子图绘制教程:subplot 用法详解
  • 警惕黄精高含量宣传造假!2026黄精品牌真实品质排行榜:临床数据支撑! - 资讯焦点
  • 2026 成都英语雅思培训教育机构推荐|雅思培训课程中心权威口碑榜单 - 老周说教育
  • 【含文档+PPT+源码】基于小程序开发的宠物寄养平台管理系统
  • 【Matlab】MATLAB plot样式设置教程:线型、标记点配置与数据曲线区分
  • NOIP2025 补全计划
  • CANN shmem 内存池设计与跨进程虚拟地址映射原理
  • 2026年比较好的银焊粉回收/贵金属废渣回收优质厂商精选推荐(口碑) - 品牌宣传支持者
  • 100多套官网HTML源码 前端静态页面源码
  • CANN shmem 在多模型共驻场景下的安全隔离架构
  • 2026年正规的小胸内衣,超薄内衣店优质品牌推荐名录 - 品牌鉴赏师
  • AI写论文快速上手!这4款AI论文生成工具,开启论文写作新体验!
  • 2026年中国访客机品牌发布:以访客云Fonkalink为代表的标杆企业深度解析 - 品牌推荐
  • 2026年第一季度时序数据库3大迁移难点全解析——从“审慎评估”到“平稳过渡”的实施路径
  • 2026 成都英语雅思培训教育机构推荐、雅思培训课程中心权威口碑榜单 - 老周说教育
  • 吃透Java操作符终阶:单目+关系+逻辑+条件+优先级 全解析
  • CANN shmem 共享内存通信模型的进程间同步机制
  • 2026 重庆英语雅思培训教育机构推荐、雅思培训课程中心权威口碑榜单 - 老周说教育
  • 时序数据库迁移的关键挑战与应对策略解析
  • CANN shmem 的原子操作语义与内存一致性保障