mongodb进阶(2):副本集

时间:2022-10-01 00:51:03

副本集(Replication Set)简单来说,是带有自动故障恢复功能的主从复制。主机会在整个集合中动态的选举产生。当一个主机失败时,整个副本集会重新选举新的机器作为主机。整个过程对用户透明,完全自动化的进行。

本实验,在上一篇文章的相同环境中完成。如果见到上一篇中提到的文件或文件夹,莫混淆。所有设计master和slave字眼的都是上一篇中的资源,本篇以node1和node2做为标识符。

第一步,在dbs目录创建node1和node2目录

第二步,在conf目录中创建node1.conf和node2.conf配置文件

第三步,修改配置文件

port = 10001
dbpath = dbs\node1
logpath = logs\node1.log
#添加多个时,直接用逗号分割,如:rset\192.168.90.7:10002,192.168.90.7:10003
replSet = rset/192.168.90.7:10002
node1.conf

port = 10002
dbpath = dbs\node2
logpath = logs\node2.log
#添加多个时,直接用逗号分割
replSet = rset/192.168.90.7:10001
node2.conf

第四步,启动服务器

bin\mongod.exe --config conf\node1.conf
启动node1

bin\mongod.exe --config conf\node2.conf
启动node2

此时,查看日志,可以看到类似如下的

Wed Mar 26 11:36:09.043 [rsStart] couldn't connect to 192.168.90.7:10002: couldn't connect to server 192.168.90.7:10002
Wed Mar 26 11:36:10.152 [rsStart] replSet can't get local.system.replset config from self or any seed (yet)
这些错误信息是因为没有初始化副本集

第五步,初始化副本集

连接副本集中的任意机器,

mongo localhost:10001
输入如下命令(其中的ip地址端口等,请替换),进行初始化

use admin
db.runCommand({"replSetInitiate":{"_id":"rset","members":[{"_id":1,"host":"192.168.90.7:10001"},{"_id":2,"host":"192.168.90.7:10002"}]}} )
这样,就完成了副本集的基本配置,观察日志可以看到整个“选举”的过程,以及主从机的确定。

Wed Mar 26 11:37:24.454 [rsMgr] replSet info electSelf 1
Wed Mar 26 11:37:25.454 [rsMgr] replSet PRIMARY
Wed Mar 26 11:37:26.454 [rsHealthPoll] replSet member 192.168.90.7:10002 is now in state RECOVERING
Wed Mar 26 11:37:28.454 [initandlisten] connection accepted from 192.168.90.7:4003 #4 (3 connections now open)
Wed Mar 26 11:37:28.532 [conn4] end connection 192.168.90.7:4003 (2 connections now open)
Wed Mar 26 11:37:29.407 [initandlisten] connection accepted from 192.168.90.7:4004 #5 (3 connections now open)
Wed Mar 26 11:37:29.532 [initandlisten] connection accepted from 192.168.90.7:4005 #6 (4 connections now open)
Wed Mar 26 11:37:30.548 [slaveTracking] build index local.slaves { _id: 1 }
Wed Mar 26 11:37:30.548 [slaveTracking] build index done. scanned 0 total records. 0 secs
Wed Mar 26 11:37:32.454 [rsHealthPoll] replSet member 192.168.90.7:10002 is now in state SECONDARY