MongoDB主从复制

来源:互联网 发布:在哪看淘宝自动售货 编辑:程序博客网 时间:2024/06/05 17:18

MongoDB的主从复制我觉得可以理解为实时备份,当然它还有切换主从服务器,用于主服务器挂掉后的临时使用功能。它的用法很简单,也是该数据库在云计算处理上十分强大的地方。下面来实践一下看看。

1、主服务器

      配置zhu.conf

     dbpath = D:\MongoDB\db1   #主数据库地址
     port = 1111 #主数据库端口号
     bind_ip = 127.0.0.1 #主数据库所在服务器
     master = true #确定我是主服务器

     zhu.bat

     mongod --config zhu.conf

2、从服务器

     配置cong.conf

    dbpath = D:\MongoDB\db2   #从数据库地址
    port = 2222 #从数据库端口号
    bind_ip = 127.0.0.1 #从数据库所在服务器
    source = 127.0.0.1:1111 #确定主数据库端口   这个配置项(source)可以用shell动态添加
    slave = true #确定自己是从服务器

     cong.bat

    mongod --config 7777.conf

3、打开顺序:主服务器,从服务器,主shell端,从shell端

4、主shell端中

      mongo 127.0.0.1:8888   

> show dbslocal  0.000GB> use foobarswitched to db foobar> db.poot.insert({name:"dddddd"})WriteResult({ "nInserted" : 1 })
5、从shell端中

> show dbs2016-07-09T21:22:04.175+0800 E QUERY    [thread1] Error: listDatabases failed:{"ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435 } :_getErrorWithCode@src/mongo/shell/utils.js:25:13Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1shellHelper.show@src/mongo/shell/utils.js:760:19shellHelper@src/mongo/shell/utils.js:650:15@(shellhelp2):1:1> rs.slaveOk()    --------------------------上面错的原因是从服务器上的数据库是不允许进行读写操作,所以就会报类似于这样的错误,这句是解决方法。> show dbsfoobar  0.000GBlocal   0.000GB> use foobarswitched to db foobar> db.poot.find(){ "_id" : ObjectId("5780fa74cf0bf9bce1f44239"), "name" : "dddddd" }

  可以看出,虽然从服务器不可以查看,但实际结果还是把主服务器的内容复制过去了。

6、其它一些配置项

--only  从节点---》 指定复制某个数据库,默认是复制全部数据库
--slavedelay  从节点---》设置主数据库同步数据的延迟(单位是秒)
--fastsync 从节点---》以主数据库的节点快照为节点启动从数据库
--autoresync 从节点---》如果不同步则从新同步数据库
--oplogSize  主节点---》设置oplog的大小(主节点操作记录存储到local的oplog中)

7、手动挂载从节点

      7.1、查看保的主节点

> use localswitched to db local> db.sources.find(){ "_id" : ObjectId("5780fa510006dc38178d308f"), "host" : "127.0.0.1:8888", "source" : "main", "syncedTo" : Timestamp(1468071571, 1) }>

    7.2、挂载到哪个主节点下

db.sources.insert({“host”:”127.0.0.1:1111”})

   7.3、删除被挂载的主节点

db.sources.remove({“host”:”127.0.0.1:1111”})

备注:主从备份中,主服务器是可以增加用户的,但是从服务器上不允许增加用户,会报下面的错。此点还没有详细看是不允许增加所有用户,还是不允许增加超级用户,暂时先不做研究

>  db.createUser({user:"dy",pwd:"123",roles:["root"]})2016-07-09T20:44:29.847+0800 E QUERY    [thread1] Error: couldn't add user: notmaster :_getErrorWithCode@src/mongo/shell/utils.js:25:13DB.prototype.createUser@src/mongo/shell/db.js:1267:15@(shell):1:1


个人感觉这种服务器配置是给一些公司读取操作并不多的使用的。它的成本很小,又可以起到备份的作用。

0 0
原创粉丝点击