MongoDB 集群-主從復制(一主二從)


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. 至此,驗證完成。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM