脚踏实地、勇往直前!
全部博文(1005)
分类: NOSQL
2015-10-13 10:49:52
注意:3.6之后的版本已经不支持这种模式,官网建议采用副本集的方式部署主从
mongo配置主从环境还是比较简单的,下面是一个配置例子.
环境:
master:192.168.56.102 hostname:node2
slave:192.168.56.103 hostname:node3
1.主库和从库上都安装mongo,具体安装步骤可以参考博文
2.启动主服务器
[mongo@node2 bin]$sudo mongod --dbpath=/db/mongodb/data --logpath=/db/mongodb/log/logs --port 10000 --master
可以采用配置文件的方式启动,主库的配置文件为master.cnf,内容如下:
port = 10000
fork = true
dbpath = /db/mongodb/data
logpath = /db/mongodb/log/logs
logappend = true
shardsvr = true
master = true
quiet = true
auth =true ##启用认证
使用配置文件的方式启动
[mongo@node2 conf]$ sudo mongod -f /db/mongodb/conf/master.cnf
3.启动从服务器
[mongo@node3 bin]$sudo mongod --dbpath=/db/mongodb_slave/data --logpath=/db/mongodb_slave/log/logs --port 10001 --slave --source 192.168.56.102:10000
从库的配置文件为slave.cnf,内容如下:
port = 10001
slave = true
fork = true
source = 192.168.56.102:10000
slavedelay = 10
autoresync = true
dbpath = /db/mongodb_slave/data
logpath = /db/mongodb_slave/log/logs
quiet = true
也可以使用配置文件启动备库
[mongo@node3 conf]$ sudo mongod -f /db/mongodb_slave/conf/slave.cnf
4.验证
主库上创建一个集合并写入数据
[mongo@node2 bin]$ ./mongo 192.168.56.102:10000
MongoDB shell version: 2.6.5
connecting to: 192.168.56.102:10000/test
> show dbs
admin 0.078GB
hxl 0.453GB
local 2.077GB
> use hxl
switched to db hxl
> db.students.insert({"name":"hxl","age":28})
WriteResult({ "nInserted" : 1 })
> db.students.insert({"name":"chenli","age":25})
WriteResult({ "nInserted" : 1 })
> db.students.find()
{ "_id" : ObjectId("561c6f19b6085d8eb47cda7c"), "name" : "hxl", "age" : 28 }
{ "_id" : ObjectId("561c6f36b6085d8eb47cda7d"), "name" : "chenli", "age" : 25 }
从库上验证
[mongo@node3 bin]$ ./mongo 192.168.56.103:10001
MongoDB shell version: 2.6.5
connecting to: 192.168.56.103:10001/test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
Questions? Try the support group
> show dbs
admin 0.078GB
hxl 0.078GB
local 0.078GB
> use hxl;
switched to db hxl
> show collections
students
> db.students.find();
{ "_id" : ObjectId("561c6f19b6085d8eb47cda7c"), "name" : "hxl", "age" : 28 }
{ "_id" : ObjectId("561c6f36b6085d8eb47cda7d"), "name" : "chenli", "age" : 25 }
可以看到数据以及在从库上查看得到.
5.主备库关闭
关闭主库
sudo mongod -f /db/mongodb/conf/master.cnf --shutdown
关闭从库
sudo mongod -f /db/mongodb_slave/conf/slave.cnf --shutdown
6.故障切换
当主库出现故障的情况下,可以执行如下的命令将从库切换为主库
[mongo@node3 bin]$sudo mongod --dbpath=/db/mongodb/data --logpath=/db/mongodb/log/logs --port 10000 --master
-- The End --