Replica Set准确讲不完全是集群,只是一个主从复制的加强版
概念如下:
primary:主节点客户端写操作发生在这里。
secondary:副本,可以负载读操作,通过复制primary的oplog来实现数据同步
arbiter:仲裁节点,作用是当primary宕掉之后从secondarys选择一个变成primary
环境准备:
linux系统版本:
$ cat /proc/version Linux version 2.6.32-358.el6.x86_64 ([email protected]) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC) ) #1 SMP Tue Jan 29 11:47:41 EST 2013
三台服务器,详情如下:
192.168.38.17 --primary 192.168.38.18 --secondary 192.168.38.19 --arbiter
mongoDB版本:
mongodb-linux-x86_64-2.6.9
安装部署:
1.配置primary.conf,secondary.conf和arbiter.conf
#primary.conf:
#primary.conf dbpath=/home/admin/data/p logpath=/home/admin/log/primary.log pidfilepath=/home/admin/data/primary.pid directoryperdb=true logappend=true replSet=testrs bind_ip=192.168.38.17 port=27017 oplogSize=10000 fork=true noprealloc=true
#secondary.conf:
#secondary.conf dbpath=/home/admin/data/s logpath=/home/admin/log/secondary.log pidfilepath=/home/admin/data/secondary.pid directoryperdb=true logappend=true replSet=testrs bind_ip=192.168.38.18 port=27017 oplogSize=10000 fork=true noprealloc=true
#arbiter.conf:
dbpath=/home/admin/data/a logpath=/home/admin/log/arbiter.log pidfilepath/home/admin/data/arbiter.pid directoryperdb=true logappend=true replSet=testrs bind_ip=192.168.38.19 port=27017 oplogSize=10000 fork=true noprealloc=true
上述配置文件最好在每个集群上都放置,这样就能保证配置文件一致
2.启动
分别在不同的节点上加载不同的配置
192.168.38.17启动:
bin/mongod -f /home/admin/mongodb/primary.conf
192.168.38.18启动:
bin/mongod -f /home/admin/mongodb/secondary.conf
192.168.38.19启动:
bin/mongod -f /home/admin/mongodb/arbiter.conf
3.登陆系统配置各个节点
bin/mongo 192.168.38.17:27017
执行如下命令:
>use admin >cfg={ "_id": "testrs", "members": [ { "_id": 0, "host": "192.168.38.17:27017", "priority": 2 }, { "_id": 1, "host": "192.168.38.18:27017", "priority": 1 }, { "_id": 2, "host": "192.168.38.19:27017", "arbiterOnly": true } ] }; >rs.initiate(cfg)
此时配置已生效,可以通过命令查看相应的信息
4.查看目前各个节点的状态:
rs.status()
结果如下:
{ "set" : "testrs", "date" : ISODate("2015-04-03T09:02:29Z"), "myState" : 1, "members" : [ { "_id" : 0, "name" : "192.168.38.17:27017", "health" : 1, "state" : 1, "stateStr" : "PRIMARY", "uptime" : 21104, "optime" : Timestamp(1428032802, 2), "optimeDate" : ISODate("2015-04-03T03:46:42Z"), "electionTime" : Timestamp(1428030689, 1), "electionDate" : ISODate("2015-04-03T03:11:29Z"), "self" : true }, { "_id" : 1, "name" : "192.168.38.18:27017", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 21070, "optime" : Timestamp(1428032802, 2), "optimeDate" : ISODate("2015-04-03T03:46:42Z"), "lastHeartbeat" : ISODate("2015-04-03T09:02:27Z"), "lastHeartbeatRecv" : ISODate("2015-04-03T09:02:28Z"), "pingMs" : 0, "syncingTo" : "192.168.38.17:27017" }, { "_id" : 2, "name" : "192.168.38.19:27017", "health" : 1, "state" : 7, "stateStr" : "ARBITER", "uptime" : 21070, "lastHeartbeat" : ISODate("2015-04-03T09:02:29Z"), "lastHeartbeatRecv" : ISODate("2015-04-03T09:02:29Z"), "pingMs" : 0 } ], "ok" : 1 }
此时配置已经完成,kill主节点之后查看状态会自动切换
PS:默认情况下副本是不会负载读操作的,如果打算让副本负载一部分读操作那么可以参见另外一篇博客