標籤:MongoDB主從架構和複製集架構
主從架構:
mongodb支援傳統的master-slave架構。master節點負責資料的讀寫,slave沒有寫入許可權。沒有自動容錯移轉功能,需要指定master和slave端,不推薦在生產中使用。
主從架構的配置
環境:CentOS6.5 MongoDB3.4
master設定檔
master.conf
dbpath=/data/mongo/masterlogpath=/var/log/mongo/master/mongodb.logport=27017bind_ip=127.0.0.1master=true fork=true //後台運行mongodb服務
slave設定檔
dbpath=/data/mongo/slavelogpath=/var/log/mongo/slave/mongodb.logport=27018bind_ip=127.0.0.1slave=truefork=true //後台運行mongodb服務source=127.0.0.1:27017 //配置主的ip和連接埠
分別啟動master和slave
mongo --config master.conf mongo --config slave.conf
分別登入master和slave
mongo 127.0.0.1:27017mongo 127.0.0.1:27018
master上執行show dbs
> show dbsadmin 0.000GBlocal 0.005GB
slave上執行show dbs報錯
> show dbs2018-04-19T11:31:35.982+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435, "codeName" : "NotMasterNoSlaveOk"} :[email protected]/mongo/shell/utils.js:25:13[email protected]/mongo/shell/mongo.js:62:1[email protected]/mongo/shell/utils.js:782:19[email protected]/mongo/shell/utils.js:672:15@(shellhelp2):1:1
這個報錯是因為預設情況下slave上沒有讀寫權限,可以在slave上執行下面的命令解決
> rs.slaveOk() //2.6版本設定方法不一樣> show dbsadmin 0.000GBlocal 0.000GB
測試:
在主庫上建立資料庫 masterslavetest 並建立一些測試資料
> use masterslaveswitched to db masterslave> for (i = 5000; i < 100000; i++) {... db.users.insert({... "i": i,... "userName": "user" + i,... ... "age": Math.floor(Math.random() * 120),... "created": new Date(),... total: Math.floor(Math.random() * 100) * i... })... }WriteResult({ "nInserted" : 1 })
在兩個執行個體上分別執行 以下命令 可以看到在兩個資料庫上的資料保持一致,這時在主要資料庫上執行CRUD等操作時,從庫資料依然與主庫一致
db.users.find()
slave上同樣執行上面的命令
測試在slave節點上面添加一條資料看看
> db.mycoll.insert({"i":9999,"username":"test","age":30})WriteResult({ "writeError" : { "code" : 10107, "errmsg" : "not master" } })
可以看到slave節點沒有寫入許可權。
關掉master上的mongo進程看看
> show dbs2018-04-19T11:58:43.464+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435, "codeName" : "NotMasterNoSlaveOk"} :[email protected]/mongo/shell/utils.js:25:13[email protected]/mongo/shell/mongo.js:62:1[email protected]/mongo/shell/utils.js:782:19[email protected]/mongo/shell/utils.js:672:15@(shellhelp2):1:1> rs.slaveOk()> > > show dbsadmin 0.000GBlocal 0.000GBmasterslave 0.005GB
slave還是沒有寫入許可權
MongoDB 主從架構和複製集架構