不安分的黑娃
踏踏实实,坚持学习,慢慢就懂了~

MongoDB 集群-主从复制(一主二从)

官方文档

版本

mongodb-linux-x86_64-ubuntu1804-5.0.4.tgz 免安装压缩包版本。

启动命令

# 属于副本集 rs0端口为 27018 的mongodb 服务
./bin/mongod --replSet=rs0 --port=27018 --bind_ip=127.0.0.1 --dbpath=/home/public/Soft/mongodb-5.0.4/primary27018db/ --logpath=/home/public/Soft/mongodb-5.0.4/primary27018db/db.log --directoryperdb --fork  > /dev/null 2>&1  &

# 属于副本集 rs0端口为 27019 的mongodb 服务
./bin/mongod --replSet=rs0 --port=27019 --bind_ip=127.0.0.1 --dbpath=/home/public/Soft/mongodb-5.0.4/slave27019db/ --logpath=/home/public/Soft/mongodb-5.0.4/slave27019db/db.log --directoryperdb  --fork  > /dev/null 2>&1  &

# 属于副本集 rs0端口为 27020 的mongodb 服务
./bin/mongod --replSet=rs0 --port=27020 --bind_ip=127.0.0.1 --dbpath=/home/public/Soft/mongodb-5.0.4/arbiter27020db/ --logpath=/home/public/Soft/mongodb-5.0.4/arbiter27020db/db.log --directoryperdb  --fork > /dev/null 2>&1  &

初始化集群

连接27018 端口的MongoDB服务:

./bin/mongo  --host=127.0.0.1 --port=27018

连接成功,控制台输出:

MongoDB shell version v5.0.3
connecting to: mongodb://127.0.0.1:27018/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c9296cbb-8005-4398-8c4c-83a11d3723cc") }
MongoDB server version: 5.0.4
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting: 
        2021-12-03T18:44:52.516+08:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2021-12-03T18:44:53.247+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2021-12-03T18:44:53.247+08:00: Soft rlimits for open file descriptors too low
        2021-12-03T18:44:53.247+08:00:         currentValue: 1024
        2021-12-03T18:44:53.247+08:00:         recommendedMinimum: 64000
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

执行初始化命令:

rs.initiate( {
   _id : "rs0",
   members: [
      { _id: 0, host: "127.0.0.1:27018" },
      { _id: 1, host: "127.0.0.1:27019" },
      { _id: 2, host: "127.0.0.1:27020" }
   ]
})

初始化成功,控制台输出:

> rs.initiate( {
...    _id : "rs0",
...    members: [
...       { _id: 0, host: "127.0.0.1:27018" },
...       { _id: 1, host: "127.0.0.1:27019" },
...       { _id: 2, host: "127.0.0.1:27020" }
...    ]
... })
{ "ok" : 1 }
rs0:SECONDARY> rs.config()
{
	"_id" : "rs0",
	"version" : 1,
	"term" : 0,
	"members" : [
		{
			"_id" : 0,
			"host" : "127.0.0.1:27018",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 1,
			"tags" : {
				
			},
			"secondaryDelaySecs" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 1,
			"host" : "127.0.0.1:27019",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 1,
			"tags" : {
				
			},
			"secondaryDelaySecs" : NumberLong(0),
			"votes" : 1
		},
		{
			"_id" : 2,
			"host" : "127.0.0.1:27020",
			"arbiterOnly" : false,
			"buildIndexes" : true,
			"hidden" : false,
			"priority" : 1,
			"tags" : {
				
			},
			"secondaryDelaySecs" : NumberLong(0),
			"votes" : 1
		}
	],
	"protocolVersion" : NumberLong(1),
	"writeConcernMajorityJournalDefault" : true,
	"settings" : {
		"chainingAllowed" : true,
		"heartbeatIntervalMillis" : 2000,
		"heartbeatTimeoutSecs" : 10,
		"electionTimeoutMillis" : 10000,
		"catchUpTimeoutMillis" : -1,
		"catchUpTakeoverDelayMillis" : 30000,
		"getLastErrorModes" : {
			
		},
		"getLastErrorDefaults" : {
			"w" : 1,
			"wtimeout" : 0
		},
		"replicaSetId" : ObjectId("61ad7b2d1b25049ef7a3b260")
	}
}

分别查看,发现 27018 是主节点,27019和27020是从节点:
image
image
image

至此 一主两从搭建完成。

验证

  1. 连接 27018 主节点,新增数据库和集合,并插入一条记录。
# 连接 27018 端口 mongodb 服务
./bin/mongo  --host=127.0.0.1 --port=27018
# 连接成功,选择 replicat_db 数据库
use replicat_db
# creplicat_db 数据库下创建 replica_tb 集合
db.createCollection("replica_tb")
# replica_tb 集合中插入2条数据
db.replica_tb.insert({name:"black",age:18,high:180.00})
db.replica_tb.insert({name:"black_01",age:20,high:180.00})

控制台输出:
image

  1. 分别连接 27019 和 27020,查看数据库:
    执行 show dbs 命令时报错:
rs0:SECONDARY> show dbs
uncaught exception: Error: listDatabases failed:{
	"topologyVersion" : {
		"processId" : ObjectId("61ad7ad0873960731110e289"),
		"counter" : NumberLong(4)
	},
	"ok" : 0,
	"errmsg" : "not master and slaveOk=false",
	"code" : 13435,
	"codeName" : "NotPrimaryNoSecondaryOk",
	"$clusterTime" : {
		"clusterTime" : Timestamp(1638760184, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	},
	"operationTime" : Timestamp(1638760184, 1)
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs/<@src/mongo/shell/mongo.js:145:19
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:97:12
shellHelper.show@src/mongo/shell/utils.js:956:13
shellHelper@src/mongo/shell/utils.js:838:15
@(shellhelp2):1:1

问题说明:
首先这是正常的,因为SECONDARY是不允许读写的, 在写多读少的应用中,使用Replica Sets来实现读写分离。通过在连接时指定或者在主库指定slaveOk,由Secondary来分担读的压力,Primary只承担写操作。

参考这篇《MongoDb的“not master and slaveok=false”错误及解决方法》博客解决。

解决方案:分别在主节点和从节点执行 db.getMongo().setSecondaryOk() 命令即可。

再次查看,没有上面的报错:
image

注意:查询数据前一定确保每个主、从节点执行 db.getMongo().setSecondaryOk() 命令都执行完成。

  1. kill 杀掉 27018端口的mongodb服务后,27020端口随后被选为主节点
    image

  2. 至此,验证完成。

posted on 2021-12-06 12:02  不安分的黑娃  阅读(1311)  评论(0编辑  收藏  举报