MongoDB主從複製

MongoDB的主從複製我覺得可以理解爲實時備份,當然它還有切換主從服務器,用於主服務器掛掉後的臨時使用功能。它的用法很簡單,也是該數據庫在雲計算處理上十分強大的地方。下面來實踐一下看看。

1、主服務器

      配置zhu.conf

     dbpath = D:\MongoDB\db1   #主數據庫地址
     port = 1111 #主數據庫端口號
     bind_ip = 127.0.0.1 #主數據庫所在服務器
     master = true #確定我是主服務器

     zhu.bat

     mongod --config zhu.conf

2、從服務器

     配置cong.conf

    dbpath = D:\MongoDB\db2   #從數據庫地址
    port = 2222 #從數據庫端口號
    bind_ip = 127.0.0.1 #從數據庫所在服務器
    source = 127.0.0.1:1111 #確定主數據庫端口   這個配置項(source)可以用shell動態添加
    slave = true #確定自己是從服務器

     cong.bat

    mongod --config 7777.conf

3、打開順序:主服務器,從服務器,主shell端,從shell端

4、主shell端中

      mongo 127.0.0.1:8888   

> show dbs
local  0.000GB
> use foobar
switched to db foobar
> db.poot.insert({name:"dddddd"})
WriteResult({ "nInserted" : 1 })
5、從shell端中

> show dbs
2016-07-09T21:22:04.175+0800 E QUERY    [thread1] Error: listDatabases failed:{
"ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435 } :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:760:19
shellHelper@src/mongo/shell/utils.js:650:15
@(shellhelp2):1:1

> rs.slaveOk()    --------------------------上面錯的原因是從服務器上的數據庫是不允許進行讀寫操作,所以就會報類似於這樣的錯誤,這句是解決方法。
> show dbs
foobar  0.000GB
local   0.000GB
> use foobar
switched to db foobar
> db.poot.find()
{ "_id" : ObjectId("5780fa74cf0bf9bce1f44239"), "name" : "dddddd" }

  可以看出,雖然從服務器不可以查看,但實際結果還是把主服務器的內容複製過去了。

6、其它一些配置項

--only  從節點---》 指定複製某個數據庫,默認是複製全部數據庫
--slavedelay  從節點---》設置主數據庫同步數據的延遲(單位是秒)
--fastsync 從節點---》以主數據庫的節點快照爲節點啓動從數據庫
--autoresync 從節點---》如果不同步則從新同步數據庫
--oplogSize  主節點---》設置oplog的大小(主節點操作記錄存儲到local的oplog中)

7、手動掛載從節點

      7.1、查看保的主節點

> use local
switched to db local
> db.sources.find()
{ "_id" : ObjectId("5780fa510006dc38178d308f"), "host" : "127.0.0.1:8888", "sour
ce" : "main", "syncedTo" : Timestamp(1468071571, 1) }
>

    7.2、掛載到哪個主節點下

db.sources.insert({“host”:”127.0.0.1:1111”})

   7.3、刪除被掛載的主節點

db.sources.remove({“host”:”127.0.0.1:1111”})

備註:主從備份中,主服務器是可以增加用戶的,但是從服務器上不允許增加用戶,會報下面的錯。此點還沒有詳細看是不允許增加所有用戶,還是不允許增加超級用戶,暫時先不做研究

>  db.createUser({user:"dy",pwd:"123",roles:["root"]})
2016-07-09T20:44:29.847+0800 E QUERY    [thread1] Error: couldn't add user: not
master :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1267:15
@(shell):1:1


個人感覺這種服務器配置是給一些公司讀取操作並不多的使用的。它的成本很小,又可以起到備份的作用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章