Mongo Replica Set集群介绍:
Replica Set使用的是n个mongod节点,构建具备自动的容错功能(auto-failover),自动恢复的(auto-recovery)的高可用方案。 如上图,Mongodb(M)表示主节点,Mongodb(S)表示备节点,Mongodb(A)表示仲裁节点。主备节点存储数据,仲裁节点不存储数据。客户端同时连接主节点与备节点,不连接仲裁节点。
默认设置下,主节点提供所有增删查改服务,备节点不提供任何服务。但是可指定读策略(本文PHP连接Mongo实例),减少主节点读压力。
Mongo Replica Set集群搭建:
(1)建立数据库文件夹、日志文件夹
mkdir /data/mongo_cluster/{master,slave,arbiter} -p
mkdir /data/mongo_cluster/master/logs
mkdir /data/mongo_cluster/slave/logs
mkdir /data/mongo_cluster/arbiter/logs
#master配置 /data/mongo_cluster/master/master.conf
dbpath=/data/mongo_cluster/master
logpath=/data/mongo_cluster/master/logs/master.log
pidfilepath=/data/mongo_cluster/master/master.pid
logappend=true
replSet=rep1
bind_ip=192.168.15.130
port=10000
fork=true
journal=true
#slave配置 data/mongo_cluster/slave/slave.conf
dbpath=/data/mongo_cluster/slave
logpath=/data/mongo_cluster/slave/logs/slave.log
pidfilepath=/data/mongo_cluster/slave/slave.pid
logappend=true
replSet=rep1
bind_ip=192.168.15.130
port=10001
fork=true
journal=true
#arbiter配置 /data/mongo_cluster/arbiter/arbiter.conf
dbpath=/data/mongo_cluster/arbiter
logpath=/data/mongo_cluster/arbiter/logs/arbiter.log
pidfilepath=/data/mongo_cluster/arbiter/arbiter.pid
logappend=true
replSet=rep1
bind_ip=192.168.15.130
port=10002
fork=true
journal=true
/usr/local/mongodb3.0.5/bin/mongod -f /data/mongo_cluster/master/master.conf
/usr/local/mongodb3.0.5/bin/mongod -f /data/mongo_cluster/slave/slave.conf
/usr/local/mongodb3.0.5/bin/mongod -f /data/mongo_cluster/arbiter/arbiter.conf
/usr/local/mongodb3.0.5/bin/mongo 192.168.15.130:10000 #登陆master执行下面命令
use admin
cfg={ _id:"rep1", members:[ {_id:0,host:'192.168.15.130:10000',priority:2}, {_id:1,host:'192.168.15.130:10001',priority:1},{_id:2,host:'192.168.15.130:10002',arbiterOnly:true}] };
rs.initiate(cfg)
rs.status()查看集群状态
rs.rs.conf()查看集群配置信息
$options = array(
//指定读策略 http://php.net/manual/zh/mongo.readpreferences.php
'readPreference' => MongoClient::RP_SECONDARY_PREFERRED,
'replicaSet' => 'rep1'
);
$mongo = new MongoClient("mongodb://192.168.15.130:10000, 192.168.15.130:10001", $options);
$rs = $mongo->selectDB("test")->getCollectionNames();
var_dump($rs);