1、副本集就是有自动故障恢复功能的主从集群。副本集当中最少保证要有两个节点副本集当中备份节点只做数据备份或者故障恢复.
2、主从集群和副本集最大的区别就是副本集没有固定的“主节点”;整个集群会选出一个“主节点”,当其挂掉后,又在剩下的从节点中选中其他节点为“主节点”,副本集总有一个活跃点(primary)和一个或多个备份节点(secondary)。
3 、以三个节点为例
节点1:
HOST:localhost:10001
Log File:D:\mongodb\logs\node1\logs.txt
Data File:D:\mongodb\dbs\node1
节点2:
HOST:localhost:10002
Log File:D:\mongodb\logs\node2\logs.txt
Data File:D:\mongodb\dbs\node2
节点3:
HOST:localhost:10003
Log File:D:\mongodb\logs\node3\logs.txt
Data File:D:\mongodb\dbs\node3
4、 启动节点
启动节点1:
mongod --dbpath D:\mongodb\dbs\node1 --logpath D:\mongodb\logs\node1\logs.txt --logappend --port 10001 --replSet itcast/localhost:10002 --master
启动节点2:
mongod --dbpath D:\mongodb\dbs\node2 --logpath D:\mongodb\logs\node2\logs.txt --logappend --port 10002 --replSet itcast/localhost:10001
mongod --dbpath D:\mongodb\dbs\node3 --logpath D:\mongodb\logs\node3\logs.txt --logappend --port 10003 --replSet itcast/localhost:10001,localhost:10002
mongo localhost:10001/admin db.runCommand({"replSetInitiate":{"_id":"itcast","members":[{"_id":1,"host":"localhost:10001","priority":3},{"_id":2,"host":"localhost:10002","priority":2},{"_id":3,"host":"localhost:10003","priority":1}]}}); #下面是有规律的 db.runCommand({ <span style="font-family: Arial, Helvetica, sans-serif;">"replSetInitiate": { "_id":"itcast", "members": [ { "_id":1, "host":"localhost:10001", "priority":3 }, { "_id":2, "host":"localhost:10002", "priority":2 }, { "_id":3, "host":"localhost:10003", "priority":1 } ] } });</span>
mongo localhost:10002 db.$cmd.findOne ( {ismaster: 1 } ); #查出副本集的详细信息
7.1、在主节点里面添加数据
mongo localhost:10001 > use itcast; > for ( var i=1;i<=10000;i++) { db.c1.insert( { name:"123",age:i } ); }
mongo localhost:10002 > use itcast; > show dbs; itcast; #从节点不可以操作数据,只是备份了数据
mongo localhost:10002 db.$cmd.findOne ( {ismaster: 1 } ); #当从节点变为了主节点,就可以操作数据了