Introduction to MongoDB Replication sets
A MongoDB replica set consists of a set of Mongod instances (processes) that contain one primary node and multiple secondary nodes, and all data from MongoDB Driver (client) is written to primary, Secondary writes data synchronously from primary to keep all members of the replication set stored in the same data set, providing high availability of data.
The client writes the data on the master node, reads the data from the node, the master node and the data from the node ensure data consistency, and if one of the nodes fails, the other nodes immediately take over the business without downtime.
Benefits of replication Sets
Make your data more secure
Engage Data availability
Disaster recovery
Maintenance without downtime (e.g. backup, rebuild index, fail over)
Read scaling (extra copy read)
The replica set is transparent to the application
Features of replication sets
n Points of the cluster
Any node can be used as the master node
All write operations are on the primary node
Auto Fail-Over
Automatic recovery
Replication Set Deployment
The Installed MongoDB
Add a configuration 4 instances
Click: Install and Example Add Tutorial
# mkdir -p /data/mongodb/mongodb{2,3,4} //创建数据目录# mkdir /data/mongodb/logs# touch /data/mongodb/logs/mongodb{2,3,4}.log //创建日志文件# cd /data/mongodb/logs/# chmod 777 *.log //赋予权限
Editing a log file for 4 instances
# cp -p /etc/mongod.conf /etc/mongod2.conf# vim /etc/mongod2.conf path: /data/mongodb/logs/mongodb2.log //每个实例指定自己日志目录 dbPath: /data/mongodb/mongodb2 //每个实例指定自己的数据目录 port: 27018 //指定端口分别为27017、 27018、 27019 、 27020 ....... replication: //开启所有实例的复制参数:定义一个 replSetName: kgcrs replSetName: kgcrs
Start all Instances
# mongod -f /etc/mongod.conf# mongo --port 27017# mongod -f /etc/mongod2.conf# mongo --port 27018# mongod -f /etc/mongod3.conf# mongo --port 27019# mongod -f /etc/mongod4.conf# mongo --port 27020# netstat -ntap | grep mongod
Initializing a configuration Replica set
To determine that no data is on the node
# mongo //进入实例 > show dbs > rs.status() //查看复制集状态 > cfg={"_id":"kgcrs","members":[{"_id":0,"host":"192.168.233.128:27017"},{"_id":1,"host":"192.168.233.128:27018"},{"_id":2,"host":"192.168.233.128:27019"}]} // 定义cfg初始化参数 id 是之前配置文件里定义的,成员(3个 id分别定义 0 1 2 IP端口号27017、27018、27019) > rs.initiate(cfg) //启动复制集 > rs.status() //查看此时可以查看到复制状态了
Adding and removing nodes
Configure startup replication sets to increase and remove nodes by Rs.add () and Rs.remove ()
Rs.add ("192.168.233.128:27020")//Add node
Rs.status ()
Rs.remove ("192.168.233.128:27020")//Delete node
# kill -9 61070 //关闭主节点 复制集会自动切换 > rs.status() //查看
MongoDB Replica Set