MongoDB复制是将数据同步在多个服务器的过程。复制提供了数据的冗余备份,并在多个服务器上存储数据副本,提高了数据的可用性, 并可以保证数据的安全性。
复制还允许您从硬件故障和服务中断中恢复数据。
版本: 各副本集服务器的MongoDB版本一致或支持同样的replSet功能
网络: 副本集内的每个成员都必须能够连接到其他成员(包括自身),启动时注意bind_ip --bind_ip_all.
配置副本集1 建立配置文件
mongodb.conf
1 # Start MongoDB as a daemon on port 27017
2
3 port = 27017
4 fork = true
5 replSet = test_replica_set
6 dbpath = /datatest/db
7 logpath = /datatest/db/test.log
8 logappend = true
9
mongodb2.conf
2
3 port = 27017
4 fork = true
5 replSet = test_replica_set
6 dbpath = /datatest/db
7 logpath = /datatest/db/test.log
8 logappend = true
9
mongodb3.conf
2
3 port = 27017
4 fork = true
5 replSet = test_replica_set
6 dbpath = /datatest/db
7 logpath = /datatest/db/test.log
8 logappend = true
9
2 启动数据库
mac-abeen:bin abeen$ sudo ./mongod -f mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 37181
child process started successfully, parent exiting
mac-abeen:bin abeen$ sudo ./mongod -f mongodb2.conf
about to fork child process, waiting until server is ready for connections.
forked process: 37185
child process started successfully, parent exiting
mac-abeen:bin abeen$ sudo ./mongod -f mongodb3.conf
about to fork child process, waiting until server is ready for connections.
forked process: 37189
child process started successfully, parent exiting
3 初始化副本集
mac-abeen:bin abeen$ ./mongo --nodb
MongoDB shell version: 3.2.8
> config = {}
{ }
> config = {"_id": "test_replica_set", "members": [
{"_id": 0, "host": "192.168.0.10:27017"},
{"_id": 1, "host": "192.168.0.20:27017"},
{"_id": 2, "host": "192.168.0.30:27017"}]}
{
"_id" : "test_replica_set",
"members" : [
{
"_id" : 0,
"host" : "192.168.0.10:27017"
},
{
"_id" : 1,
"host" : "192.168.0.20:27017"
},
{
"_id" : 2,
"host" : "192.168.0.30:27017"
}
]
}
> db = (new Mongo("192.168.0.10:27017")).getDB("test")
test
> rs.initiate(config)
{ "ok" : 1 }
test_replica_set:OTHER>
test_replica_set:PRIMARY> rs.config()
{
"_id" : "test_replica_set",
"version" : 1,
"protocolVersion" : NumberLong(1),
"members" : [
{
"_id" : 0,
"host" : "192.168.0.10:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "192.168.0.20:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "192.168.0.30:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"getLastErrorModes" : {
},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5850f445c8cacd70496883b0")
}
}
4 写入数据并查看副本集数据