1. 程式人生 > 實用技巧 >MongoDB replication set 叢集搭建

MongoDB replication set 叢集搭建

用一臺機器的不同埠,模擬MongoDB replication set 叢集搭建(最少需要四臺)

1:配置檔案

Primary(主機)的配置檔案(primary.conf)

#mongodb.conf
dbpath=/opt/module/mongodb/rs/data/p0
logpath=/opt/module/mongodb/rs/logs/primary.log

logappend=true
fork = true
port = 27117

noauth = true
#auth = true

#journal=true
nojournal=true

replSet=rs

pidfilepath=/opt/module/mongodb/rs/pids/primary.pid

oplogSize
=100 directoryperdb=true

Secondary0(從機一)的配置檔案(secondary0.conf)

#mongodb.conf
dbpath=/opt/module/mongodb/rs/data/s0
logpath=/opt/module/mongodb/rs/logs/secondary0.log

logappend=true
fork = true
port = 27118

noauth = true
#auth = true

#journal=true
nojournal=true

replSet=rs

pidfilepath=/opt/module/mongodb/rs/pids/secondary0.pid

oplogSize
=100 directoryperdb=true

Secondary1(從機二)的配置檔案(secondary1.conf)

dbpath=/opt/module/mongodb/rs/data/s1
logpath=/opt/module/mongodb/rs/logs/secondary1.log

logappend=true
fork = true
port = 27119

noauth = true
#auth = true

#journal=true
nojournal=true

replSet=rs

pidfilepath=/opt/module/mongodb/rs/pids/secondary1.pid

oplogSize
=100 directoryperdb=true

arbiter(裁判機)的配置檔案(arbiter.conf)

dbpath=/opt/module/mongodb/rs/data/a0
logpath=/opt/module/mongodb/rs/logs/arbiter.log

logappend=true
fork = true
port = 27120

noauth = true
#auth = true

#journal=true
nojournal=true

replSet=rs

pidfilepath=/opt/module/mongodb/rs/pids/arbiter.pid

oplogSize=100
directoryperdb=true

2:建立相應的資料資料夾,日誌檔案

mkdir p0 s0 s1 a0

touch primary.log secondary0.log secondary1.log arbiter.log

3:啟動mongodb資料庫。4個分別啟動。檢查是否啟動成功.

bin/mongod --config /opt/module/mongodb/rs/conf/primary.conf
bin/mongod --config /opt/module/mongodb/rs/conf/secondary0.conf
bin/mongod --config /opt/module/mongodb/rs/conf/secondary1.conf
bin/mongod --config /opt/module/mongodb/rs/conf/arbiter.conf

4:登入資料庫 :

bin/mongo --port 27117

5:初始化資料庫. priority 越大 優先順序越高,就是主機。

要進去admin資料庫後才能執行初始化函式.(use admin)

rs.initiate(
   {
      _id: "rs",
      members: [
         { _id: 0, host : "192.168.1.202:27117",priority:3 },
         { _id: 1, host : "192.168.1.202:27118",priority:1 },
         { _id: 2, host : "192.168.1.202:27119",priority:1 },
         { _id: 3, host : "192.168.1.202:27120",arbiterOnly:true }
      ]
   }
)

在從機上執行rs.slaveOk() 這樣從機才能讀資料庫.