用一台机器的不同端口,模拟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() 这样从机才能读数据库.
6:查看集群状态 rs.isMaster()