MongoDB-主从复制

Master-Slave复制(主从)
关闭iptables,selinux
MongoDB主从:

启动MongoDB主从:

首先在准备好的Slave主机上的家目录中添加如下内容,启用写操作(不提前做这一步骤,数据会同步不了)。

vi ~/.mongorc.js #用户家目录
增加一行rs.slaveOk();

会发现语句没有同步,解决方法如下:

/opt/master/bin/mongod --dbpath /data/master/ --logpath /opt/master/log/mongodb.log --fork --rest --master /opt/slave1/bin/mongod --dbpath /data/slave1/ --logpath /opt/slave1/log/mongodb.log --fork --rest --slave --source 192.168.0.108:27017 --port 27017 /opt/slave2/bin/mongod --dbpath /data/slave2/ --logpath /opt/slave2/log/mongodb.log --fork --rest --slave --source 192.168.0.108:27017 --port 27017
  1. 关闭MongoDB主从:
    /opt/master/bin/mongod –shutdown –dbpath /data/master/
    /opt/slave1/bin/mongod –shutdown –dbpath /data/slave1/
    /opt/slave2/bin/mongod –shutdown –dbpath /data/slave2/
  2. 登录MongoShell
    /opt/master/bin/mongo 127.0.0.7:27017
    /opt/slave1/bin/mongo 127.0.0.7:27017
    /opt/slave2/bin/mongo 127.0.0.7:27017
    Master执行如下语句:
    > show dbs;
    admin 0.000GB
    local 0.000GB
    > use wgl;
    switched to db wgl
    > db.wgl.insert({“1”:”1”});
    WriteResult({ “nInserted” : 1 })
    > db.wgl.find();
    { “_id” : ObjectId(“58ecf611af68dee41cf74762”), “1” : “1” }
    > show dbs;
    admin 0.000GB
    local 0.000GB
    wgl 0.000GB

    登录任意Slave:数据已同步
    > show dbs;
    admin 0.000GB
    local 0.000GB
    wgl 0.000GB
    > use wgl;
    switched to db wgl
    > db.wgl.find();
    { “_id” : ObjectId(“58ecf611af68dee41cf74762”), “1” : “1” }
    查看Master地址:
    > use local;
    switched to db local
    > db.sources.find();
    { “_id” : ObjectId(“58ecf7e95b2d1843b38de645”), “host” : “192.168.0.108:27017”, “source” : “main”, “syncedTo” : Timestamp(1491925772, 1) }

    db.printReplicationInfo(); #查看主备状态(默认10秒进行一次同步)
    > db.printReplicationInfo();
    this is a slave, printing slave replication info.
    source: 192.168.0.108:27017
    syncedTo: Tue Apr 11 2017 23:50:12 GMT+0800 (CST)
    6 secs (0 hrs) behind the freshest member (no primary available at the moment)

    如果出现不同步现象,可按如下步骤进行:

1.杀死MongoDB进程

2.单实例方式启动服务:/opt/slave2/bin/mongod –dbpath /data/slave2/ –logpath /opt/slave2/log/mongodb.log –fork –rest

3./opt/slave2/bin/mongo #进程nosql的shell中,删除所有数据库。

> show dbs;
admin 0.000GB
local 0.000GB
> use admin;
switched to db admin
> db.dropDatabase();
{ “dropped” : “admin”, “ok” : 1 }
> use local;
switched to db local
> db.dropDatabase();
{ “dropped” : “local”, “ok” : 1 }
> exit

4.在家目录输出

vim ~/.mongorc.js #用户家目录
增加一行rs.slaveOk();
echo “rs.slaveOk();” >> .mongors.js

启动Slave2:

/opt/slave2/bin/mongod –dbpath /data/slave2/ –logpath /opt/slave2/log/mongodb.log –fork –rest –slave –source 192.168.0.108:27017 –port 27017

5.问题解决

版权声明:
作者:WangGaoli
链接:https://wanggaoli.com/2806.html
来源:王高利的个人博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>