MongoDB Replication 副本集搭建

版本:针对MongoDB 5.0

官方文档:https://docs.mongodb.com/manual/tutorial/deploy-replica-set/#overview

第一步:准备三台服务器 (副本集应该总是有奇数个成员。确保选举的顺利进行)

192.168.223.133 PRIMARY
192.168.223.134 SECONDARY
192.168.223.135 SECONDARY

# 分别修改主机名
192.168.223.133 hostnamectl set-hostname mongodb01.node
192.168.223.134 hostnamectl set-hostname mongodb02.node
192.168.223.135 hostnamectl set-hostname mongodb03.node

# 分别配置/etc/hosts
vim /etc/hosts
    ## 在hosts文件中增加下面的配置
    192.168.223.133 mongodb01.node
    192.168.223.134 mongodb02.node
    192.168.223.135 mongodb03.node

第二步:安装MongoDB,增加副本集参数配置

# 安装mongodb
sudo yum install -y mongodb-org

# 设置防火墙
firewall-cmd --zone=public --add-port=27017/tcp --permanent
firewall-cmd --reload

# 修改配置文件/etc/mongod.conf 
# mongod.conf
...
# 修改bindIp
net:
  port: 27017
  bindIp: localhost,mongodb01.node # 绑定本机的IP或者主机名

# 副本集配置
replication:
  oplogSizeMB: 102 # 对于64位系统,oplog通常是可用磁盘空间的5%。
  replSetName: rs0
   
# 启动/重新启动mongodb 
systemctl start mongod
systemctl restart mongod

第三步:副本集初始化以及配置

# 随便连接一个mongodb实例
mongo mongodb://mongodb01.node:27017/test

# 使用rs.help()可以查看副本集所有的操作方法
> rs.help()

# 初始化副本集 此处需要注意第一个"_id"表示副本集的名称,就是配置文件中配置的”replSetName“
> rs.initiate({_id:'rs0',members:[
    {_id:1,host:'mongodb01.node:27017'},
    {_id:3,host:'mongodb02.node:27017'},
    {_id:2,host:'mongodb03.node:27017'}
]})

# 当然也可以选择先配置一个节点 然后加入使用rs.add()加入其他节点, 如下:
> rs.initiate({_id:'rs0',members:[{_id:1,host:'mongodb01.node:27017'}]})
rs0:PRIMARY> rs.add('mongodb02.node:27017')
rs0:PRIMARY> rs.add('mongodb03.node:27017')

# 初始化以后会看到客户端shell变成了”rs0:PRIMARY“

# 使用rs.status()查看副本集群的状态 
# mongodb01.node:27017状态: "PRIMARY"
# mongodb02.node:27017和mongodb03.node:27017状态: "SECONDARY"
rs0:SECONDARY> rs.status()
{
        "set" : "rs0",
        "date" : ISODate("2021-12-15T07:33:26.513Z"),
        "myState" : 1,
        "term" : NumberLong(2),
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "majorityVoteCount" : 2,
        "writeMajorityCount" : 2,
        "votingMembersCount" : 3,
        "writableVotingMembersCount" : 3,
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1639553603, 1),
                        "t" : NumberLong(2)
                },
                "lastCommittedWallTime" : ISODate("2021-12-15T07:33:23.687Z"),
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1639553603, 1),
                        "t" : NumberLong(2)
                },
                "appliedOpTime" : {
                        "ts" : Timestamp(1639553603, 1),
                        "t" : NumberLong(2)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1639553603, 1),
                        "t" : NumberLong(2)
                },
                "lastAppliedWallTime" : ISODate("2021-12-15T07:33:23.687Z"),
                "lastDurableWallTime" : ISODate("2021-12-15T07:33:23.687Z")
        },
        "lastStableRecoveryTimestamp" : Timestamp(1639553549, 1),
        "electionCandidateMetrics" : {
                "lastElectionReason" : "stepUpRequestSkipDryRun",
                "lastElectionDate" : ISODate("2021-12-15T07:33:03.635Z"),
                "electionTerm" : NumberLong(2),
                "lastCommittedOpTimeAtElection" : {
                        "ts" : Timestamp(1639553575, 1),
                        "t" : NumberLong(1)
                },
                "lastSeenOpTimeAtElection" : {
                        "ts" : Timestamp(1639553575, 1),
                        "t" : NumberLong(1)
                },
                "numVotesNeeded" : 2,
                "priorityAtElection" : 1,
                "electionTimeoutMillis" : NumberLong(10000),
                "priorPrimaryMemberId" : 1,
                "numCatchUpOps" : NumberLong(0),
                "newTermStartDate" : ISODate("2021-12-15T07:33:03.671Z"),
                "wMajorityWriteAvailabilityDate" : ISODate("2021-12-15T07:33:03.699Z")
        },
        "electionParticipantMetrics" : {
                "votedForCandidate" : true,
                "electionTerm" : NumberLong(1),
                "lastVoteDate" : ISODate("2021-12-15T07:26:29.091Z"),
                "electionCandidateMemberId" : 1,
                "voteReason" : "",
                "lastAppliedOpTimeAtElection" : {
                        "ts" : Timestamp(1639553178, 1),
                        "t" : NumberLong(-1)
                },
                "maxAppliedOpTimeInSet" : {
                        "ts" : Timestamp(1639553178, 1),
                        "t" : NumberLong(-1)
                },
                "priorityAtElection" : 1
        },
        "members" : [
                {
                        "_id" : 1,
                        "name" : "mongodb01.node:27017",
                        "health" : 0,
                        "state" : 8,
                        "stateStr" : "(not reachable/healthy)",
                        "uptime" : 0,
                        "optime" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastAppliedWallTime" : ISODate("2021-12-15T07:33:13.685Z"),
                        "lastDurableWallTime" : ISODate("2021-12-15T07:33:13.685Z"),
                        "lastHeartbeat" : ISODate("2021-12-15T07:33:25.726Z"),
                        "lastHeartbeatRecv" : ISODate("2021-12-15T07:33:18.704Z"),
                        "pingMs" : NumberLong(1),
                        "lastHeartbeatMessage" : "Error connecting to mongodb01.node:27017 (192.168.223.133:27017) :: caused by :: Connection refused",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 1,
                        "configTerm" : 2
                },
                {
                        "_id" : 2,
                        "name" : "mongodb03.node:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 428,
                        "optime" : {
                                "ts" : Timestamp(1639553603, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1639553603, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDate" : ISODate("2021-12-15T07:33:23Z"),
                        "optimeDurableDate" : ISODate("2021-12-15T07:33:23Z"),
                        "lastAppliedWallTime" : ISODate("2021-12-15T07:33:23.687Z"),
                        "lastDurableWallTime" : ISODate("2021-12-15T07:33:23.687Z"),
                        "lastHeartbeat" : ISODate("2021-12-15T07:33:25.715Z"),
                        "lastHeartbeatRecv" : ISODate("2021-12-15T07:33:25.714Z"),
                        "pingMs" : NumberLong(1),
                        "lastHeartbeatMessage" : "",
                        "syncSourceHost" : "mongodb02.node:27017",
                        "syncSourceId" : 3,
                        "infoMessage" : "",
                        "configVersion" : 1,
                        "configTerm" : 2
                },
                {
                        "_id" : 3,
                        "name" : "mongodb02.node:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 632,
                        "optime" : {
                                "ts" : Timestamp(1639553603, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDate" : ISODate("2021-12-15T07:33:23Z"),
                        "lastAppliedWallTime" : ISODate("2021-12-15T07:33:23.687Z"),
                        "lastDurableWallTime" : ISODate("2021-12-15T07:33:23.687Z"),
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1639553583, 1),
                        "electionDate" : ISODate("2021-12-15T07:33:03Z"),
                        "configVersion" : 1,
                        "configTerm" : 2,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                }
        ],
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1639553603, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1639553603, 1)
}

第四步:测试数据同步

## 主节点操作:
# 新建并切换数据库 my
rs0:PRIMARY> use my
# 新建集合并插入数据 
rs0:PRIMARY> db.col00.insert({name:"user01"})

## 从节点操作
# 从节点默认不能查询操作 需要执行rs.secondaryOk()允许操作
rs0:SECONDARY> rs.secondaryOk()
# 查询主节点创建的数据 如果可以查到说明搭建成功
rs0:SECONDARY> db.col00.find()

第四步:测试风险转移

## 将主节点mongodb01.node:27017实例关闭
systeml stop mongod

# 连接从节点mongodb02.node:27017查看集群状态 发现mongodb02.node:27017成为了主节点
rs0:PRIMARY> rs.status()
{
        "set" : "rs0",
        "date" : ISODate("2021-12-13T07:05:56.087Z"),
        "myState" : 1,
        "term" : NumberLong(2),
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "majorityVoteCount" : 2,
        "writeMajorityCount" : 2,
        "votingMembersCount" : 3,
        "writableVotingMembersCount" : 3,
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1639379146, 1),
                        "t" : NumberLong(2)
                },
                "lastCommittedWallTime" : ISODate("2021-12-13T07:05:46.369Z"),
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1639379146, 1),
                        "t" : NumberLong(2)
                },
                "appliedOpTime" : {
                        "ts" : Timestamp(1639379146, 1),
                        "t" : NumberLong(2)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1639379146, 1),
                        "t" : NumberLong(2)
                },
                "lastAppliedWallTime" : ISODate("2021-12-13T07:05:46.369Z"),
                "lastDurableWallTime" : ISODate("2021-12-13T07:05:46.369Z")
        },
        "lastStableRecoveryTimestamp" : Timestamp(1639379146, 1),
        "electionCandidateMetrics" : {
                "lastElectionReason" : "stepUpRequestSkipDryRun",
                "lastElectionDate" : ISODate("2021-12-13T07:05:26.351Z"),
                "electionTerm" : NumberLong(2),
                "lastCommittedOpTimeAtElection" : {
                        "ts" : Timestamp(1639379123, 1),
                        "t" : NumberLong(1)
                },
                "lastSeenOpTimeAtElection" : {
                        "ts" : Timestamp(1639379123, 1),
                        "t" : NumberLong(1)
                },
                "numVotesNeeded" : 2,
                "priorityAtElection" : 1,
                "electionTimeoutMillis" : NumberLong(10000),
                "priorPrimaryMemberId" : 1,
                "numCatchUpOps" : NumberLong(0),
                "newTermStartDate" : ISODate("2021-12-13T07:05:26.365Z"),
                "wMajorityWriteAvailabilityDate" : ISODate("2021-12-13T07:05:26.372Z")
        },
        "members" : [
                {
                        "_id" : 1,
                        "name" : "192.168.223.133:27017",
                        "health" : 0,
                        "state" : 8,
                        "stateStr" : "(not reachable/healthy)",
                        "uptime" : 0,
                        "optime" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastAppliedWallTime" : ISODate("2021-12-13T07:05:36.368Z"),
                        "lastDurableWallTime" : ISODate("2021-12-13T07:05:36.368Z"),
                        "lastHeartbeat" : ISODate("2021-12-13T07:05:54.436Z"),
                        "lastHeartbeatRecv" : ISODate("2021-12-13T07:05:41.406Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "Error connecting to 192.168.223.133:27017 :: caused by :: Connection refused",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 11,
                        "configTerm" : 2
                },
                {
                        "_id" : 2,
                        "name" : "192.168.223.129:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 4548,
                        "optime" : {
                                "ts" : Timestamp(1639379146, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDate" : ISODate("2021-12-13T07:05:46Z"),
                        "lastAppliedWallTime" : ISODate("2021-12-13T07:05:46.369Z"),
                        "lastDurableWallTime" : ISODate("2021-12-13T07:05:46.369Z"),
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1639379126, 1),
                        "electionDate" : ISODate("2021-12-13T07:05:26Z"),
                        "configVersion" : 11,
                        "configTerm" : 2,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                },
                {
                        "_id" : 3,
                        "name" : "192.168.223.130:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 1139,
                        "optime" : {
                                "ts" : Timestamp(1639379146, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1639379146, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDate" : ISODate("2021-12-13T07:05:46Z"),
                        "optimeDurableDate" : ISODate("2021-12-13T07:05:46Z"),
                        "lastAppliedWallTime" : ISODate("2021-12-13T07:05:46.369Z"),
                        "lastDurableWallTime" : ISODate("2021-12-13T07:05:46.369Z"),
                        "lastHeartbeat" : ISODate("2021-12-13T07:05:54.414Z"),
                        "lastHeartbeatRecv" : ISODate("2021-12-13T07:05:54.419Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncSourceHost" : "192.168.223.129:27017",
                        "syncSourceId" : 2,
                        "infoMessage" : "",
                        "configVersion" : 11,
                        "configTerm" : 2
                }
        ],
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1639379146, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1639379146, 1)
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,884评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,755评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,369评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,799评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,910评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,096评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,159评论 3 411
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,917评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,360评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,673评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,814评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,509评论 4 334
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,156评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,882评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,123评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,641评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,728评论 2 351

推荐阅读更多精彩内容