搭建mongodb副本集
因为机器有限,我们在同一台机器上面模拟副本集的搭建。
主机地址:10.1.10.31
创建数据库文件目录:
Standard1 : Mkdir -p /usr/local/liuwbdb/standard1/db Mkdir –p /usr/local/liuwbdb/standard1/log Standard2: Mkdir -p /usr/local/liuwbdb/standard2/db Mkdir –p /usr/local/liuwbdb/standard2/log Arbiter: Mkdir –p /usr/local/liuwbdb/arbiter/db Mkdir –p /usr/local/liuwbdb/arbiter/log
因为在同一台主机上面所以对于不同的端口:
Arbiter=>27080; Standard1 => 27081; Standard2=> 27082;
启动三个服务:
mongod -dbpath /usr/local/liuwbdb/standard1/db -logpath /usr/local/liuwbdb/standard1/log/log.txt -port 27081 -replSet liuwb -fork -logappend mongod -dbpath /usr/local/liuwbdb/standard2/db -logpath /usr/local/liuwbdb/standard2/log/log.txt -port 27082 -replSet liuwb -fork –logappend mongod -dbpath /usr/local/liuwbdb/arbiter/db -logpath /usr/local/liuwbdb/arbiter/log/log.txt -port 27080 -replSet liuwb -fork -logappend
初始化副本集:
db.runCommand({"replSetInitiate":{"_id":"liuwb","members":[{"_id":0,"host":"127.0.0.1:27081"},{"_id":1,"host":"127.0.0.1:27082"}]}});
添加仲裁:
Rs.addArb(“127.0.0.1:27080”);
查看状态:
Rs.status();
添加新服务器:
mongod -dbpath /usr/local/liuwbdb/standard3/db -logpath /usr/local/liuwbdb/standard3/log/log.txt -port 27085 -replSet liuwb -fork –logappend rs.add(“10.1.10.31:27083”);
故障切换:
rs.stepDown();
执行此命令,在查看状态会发现主已经切换到了其他服务器。
在php中测试副本集:
$conn = new Mongo("mongodb://10.1.10.31:27080,10.1.10.31:27081,10.1.10.31:27082/test"); $db= $conn->selectDb('test'); $collection = $db->selectCollection('test'); $data = array('name'=>'ximu','sex'=>1,'age'=>23); try{ $collection->insert($data,true); }catch(MongoCursorException $e){ echo $e->getMessage(); }