一旦mongod节点启动,我们将发出一个命令,以正确地初始化设置。几秒钟后,将选举产生一个主节点,你就可以开始写和查询集。
环境描述:
a.192.168.30.112:3306 主节点
b.192.168.30.113:3306 从节点
c.192.168.30.114:3306 从节点
[root@localhost ~]# tar zxvf mongodb-linux-x86_64-2.0.4.tgz
[root@localhost ~]# mv mongodb-linux-x86_64-2.0.4 /usr/local/mongodb
[root@localhost ~]# cd /usr/local/mongodb/
[root@localhost mongodb]# mkdir -p mongodb_data/mongodb_db
[root@localhost mongodb]# mkdir mongodb_data/mongodb_logs
以上3台服务器,一样的安装步骤
2.设置启动配置文件
[root@localhost mongodb]# vi /etc/mongodb.conf
fork = true
quiet = true
bind_ip = 192.168.30.112
port = 3306
dbpath = /usr/local/mongodb/mongodb_data/mongodb_db
logpath = /usr/local/mongodb/mongodb_data/mongodb_logs/server1.log
logappend = true
journal = true
rest = true
replSet = test
其余2台服务器,修改相应IP即可
3.启动mongodb
[root@localhost ~]# /usr/local/mongodb/bin/mongod -f /etc/mongodb.conf
4.初始化节点
我们连接到其中一个节点上,并使用replSetInitiate命令进行初始化。此命令需要一个配置对象,指定设定的每个成员的名字。
>/usr/local/mongodb/bin/mongo 192.168.30.112:3306/admin
>config ={_id:"test",members:[
...{_id:0,host:'192.168.30.112:3306',priority:4},
...{_id:1,host:'192.168.30.113:3306',priority:2},
...{_id:2,host:'192.168.30.114:3306',priority:1}]
...}
>rs.initiate(config);
{
"info":"Config now saved locally. Should come online in about a minute.",
"ok":1
}
PRIMARY> rs.status()
{
"set" : "test",
"date" : ISODate("2013-12-31T07:49:39Z"),
"myState" : 1,
"members" : [
{
"_id" : 0,
"name" : "192.168.30.112:3306",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"optime" : {
"t" : 1388474768000,
"i" : 1
},
"optimeDate" : ISODate("2013-12-31T07:26:08Z"),
"self" : true
},
{
"_id" : 1,
"name" : "192.168.30.113:3306",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 790,
"optime" : {
"t" : 1388474768000,
"i" : 1
},
"optimeDate" : ISODate("2013-12-31T07:26:08Z"),
"lastHeartbeat" : ISODate("2013-12-31T07:49:38Z"),
"pingMs" : 0
},
{
"_id" : 2,
"name" : "192.168.30.114:3306",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 786,
"optime" : {
"t" : 1388474768000,
"i" : 1
},
"optimeDate" : ISODate("2013-12-31T07:26:08Z"),
"lastHeartbeat" : ISODate("2013-12-31T07:49:38Z"),
"pingMs" : 0
}
],
"ok" : 1
}
现在我们来测试一下,向主节点中写点东西。
PRIMARY> db.test.save({c:3})
PRIMARY> db.test.find()
{ "_id" : ObjectId("52c2709235dd31988bc3e7c5"), "b" : 2 }
{ "_id" : ObjectId("52c2719035dd31988bc3e7c6"), "c" : 3 }
SECONDARY> db.test.find()
error: { "$err" : "not master and slaveok=false", "code" : 13435 }
错误解决办法:
在主库上设置 slaveok=ok
PRIMARY> db.getMongo().setSlaveOk();
这时候你去看看辅节点上的日志,你将会看到内容被复制了。