MongoDB 副本集搭建

最近一段一直在研究mongodb,今天试着搭建了副本集,期间遇到不少坑,目前只有两台机器,后面慢慢再添加

  先在两个机器上分别准备好配置文件(因为一个是在我自己的电脑,另外一个是在一个已经离职的同事的电脑上,所以配置看着比较乱)

 我电脑上的配置: 1.conf

#master.conf
dbpath=D:
eplSetConfdatamaster
logpath=D:
eplSetConfdatamaster.log
pidfilepath=D:
eplSetConfdatamaster.pid
directoryperdb=true
logappend=true
replSet=testrs
bind_ip=192.168.95.253
port=3000
oplogSize=10000
noprealloc=true

    同事电脑上的配置 :2.conf

#slaver.conf  
dbpath=C:Program FilesMongoDBServer3.2dataslaver
logpath=C:Program FilesMongoDBServer3.2dataslaver.log
pidfilepath=C:Program FilesMongoDBServer3.2dataslaver.pid
directoryperdb=true  
logappend=true  
replSet=testrs  
bind_ip=192.168.95.184  
port=3000
oplogSize=10000
noprealloc=true

   这里面的坑就是 bind_ip 这个值的设置 ,之前我设置的是localhost,但是在后面rs.initate(config)的时候会出现问题,待会细说,这是坑1

 配置完之后就要分别启动了服务了

D:Program FilesMongoDBServer3.2in> mongod -f 1.conf
note: noprealloc may hurt performance in many applications
C:Program FilesMongoDBServer3.2in> mongod -f 2.conf
note: noprealloc may hurt performance in many applications

启动后会弹出这个note...

   后面就是配置这个副本集,重新进一个shell  我自己电脑的:

         C:UsersArthur>mongo 192.168.95.253:3000 (这个地方由于我配置的环境变量,所以直接输入就行了)

连上之后 :

config={
"_id":"testrs",
"members":[
{"_id":0,"host":"192.168.95.184:3000"},
{"_id":1,"host":"192.168.95.253:3000"}
]    }

rs.initiate(config)

  这个时候 如果之前1.conf 里面是localhost 就会提示下面这样的错误 :

No host described in new configuration 1 for replica set replset maps to this node
{
       "ok" : 0,
       "errmsg" : "No host described in new configuration 1 for replica set replset maps to this node",
       "code" : 93
}

     之后看了看了端口

 发现这里竟然区分127.0.0.1和192.168.95.253(本机内网ip) 抱着试试的态度,把1.conf 2.conf 和config 这个配置变量里面的host地址改为一致,一看果然OK 

配置完后  你在主节点能进行一系列操作

 副本节点操作 会提示 not master and slaveok=false   查询后发现是因为SECONDARY是不允许读写的  因此设置如下即可 

  testrs:SECONDARY>  rs.slaveOk();

至此主节点的数据  副本节点应该都能访问到。 目前还有正在学习中,所述必有不严格之处,敬请指正

原文地址:https://www.cnblogs.com/ArthurXml/p/6101684.html