MongoDB主从复制(Master-Slave Replication)简单实现

MongoDB主从复制(Master-Slave Replication)其结构类似MySQL的主从复制

os:CentOS 6.5
mongodb:3.2.10


〇 搭建

master上:

  1. $ mkdir -p /data/testdb
  2. $ mongod --dbpath=/data/testdb/ --logpath=/data/testdb/master.log --fork --master 


slave上:

  1. $ mkdir -p /data/testdb
  2. $ mongod --dbpath=/data/testdb/ --logpath=/data/testdb/slave.log --fork --slave --source 192.168.0.1:27017 



然后查看一下slave的log

  1. $ tail -f /data/testdb/slave.log



如看到如下输出,则表示已经开始同步

  1. 2016-11-09T16:19:46.695+0800 I REPL [replslave] syncing from host:192.168.0.1:27017


〇 测试
master上:

  1. > use test;
  2. switched to db test
  3. > db.test_tb.insert({"master":"123456"})
  4. WriteResult({ "nInserted" : 1 })
  5. > db.test_tb.find();
  6. { "_id" : ObjectId("5822d3507fedcba43d3b9278"), "master" : "123456" }



slave上:

  1. > use test;
  2. switched to db test
  3. > db.test_tb.find();
  4. Error: error: { "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435 }



出现如上错误是因为默认slave是不可读写的:
可以执行

  1. > db.getMongo().setSlaveOk()

或者输入上命令同义词:

  1. > rs.slaveOk()


便可以了

  1. > db.test_tb.find();
  2. { "_id" : ObjectId("5822d3507fedcba43d3b9278"), "master" : "123456" }

在mongodb 3.2 文档里明确写道:

  1. WARNING
  2. Deprecated since version 3.2: MongoDB 3.2 deprecates the use of master-slave replication for components of sharded clusters.
  3. IMPORTANT
  4. Replica sets replace master-slave replication for most use cases. If possible, use replica sets rather than master-slave replication for all new production deployments. This documentation remains to support legacy deployments and for archival purposes only.


如果要用m-s结构做分片集群,可以取而代之的是使用加流弊的Replica Set,然而Replica Set可以理解为“Master-Slave”带有自动failover等功能的高级解决方案。


〇 参考文档

相关推荐