本文共 2288 字,大约阅读时间需要 7 分钟。
数据存储是整个系统中非常重要的一部分,在MySQL、Redis中都有主从架构,能够在一定程度上保证数据的安全性和高可用性,而MongoDB中也是有这种实现方式。主从配置非常简单,但是随着技术的发展已经很少采用主从架构,而更多的是采用副本集或者集群的模式去实现高可用。
简单的介绍一下MongoDB主从实现的方式和
环境:
操作系统:CentOS 6.7
MongoDB: 3.4.5
主数据目录:/data/mongomaster
从数据目录: /data/mongoslave
MongoDB 管理命令环境变量:
1 | export PATH= "$PATH:/home/mongodb/mongodb/mongodb-3.4.5/bin" |
启动主
1 2 3 4 5 6 | mongod --dbpath= /data/mongomaster/ --port 10000 --master --logpath= /data/mongomaster/masterlog --logappend --fork bout to fork child process, waiting until server is ready for connections. forked process: 3114 child process started successfully, parent exiting [root@bogon data] # |
启动从
1 2 3 4 | mongod --dbpath= /data/mongoslave/ --logpath= /data/mongoslave/slave .log --logappend --port 10002 --slave -- source 192.168.1.130:10000 --fork about to fork child process, waiting until server is ready for connections. forked process: 3144 child process started successfully, parent exiting |
测试 在主库上面创建mongo库 winne集合插入文档数据
1 2 3 4 5 6 7 8 9 10 11 | > use mongo switched to db mongo > show dbs admin 0.000GB local 0.003GB master 0.002GB > db mongo > for (i=0;i<10000;i++)db.mongo.insert({ "name" : "linux" }, { "object" : "docker" }, { "age" :i}) WriteResult({ "nInserted" : 1 }) > |
从库测试
1 2 3 4 5 6 7 8 9 10 11 12 | > show dbs 2017-05-20T14:14:42.526+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not master and slaveOk=false" , "code" : 13435, "codeName" : "NotMasterNoSlaveOk" } : _getErrorWithCode@src /mongo/shell/utils .js:25:13 Mongo.prototype.getDBs@src /mongo/shell/mongo .js:62:1 shellHelper.show@src /mongo/shell/utils .js:769:19 shellHelper@src /mongo/shell/utils .js:659:15 @(shellhelp2):1:1, |
报错了什么情况呢?找找资料什么的,关键信息not master and slaveOk=false 和NotMasterNoSlaveOk 随便一搜,结果好多这个报错呢,都是说主从这种架构默认从库不支持读写,像Redis等是不支持写,MongoDB是更神奇,直接不能读,从从库上简单的配置一下,再看看。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 2017-05-20T14:17:40.067+0800 E QUERY [thread1] SyntaxError: illegal character @(shell):1:1 > rs.slaveOk() > show dbs admin 0.000GB local 0.000GB master 0.002GB mongo 0.000GB 2017-05-20T14:17:40.067+0800 E QUERY [thread1] SyntaxError: illegal character @(shell):1:1 > rs.slaveOk() > show dbs admin 0.000GB local 0.000GB master 0.002GB mongo 0.000GB |
经过验证数据同步
本文转自 tianya1993 51CTO博客,原文链接:http://blog.51cto.com/dreamlinux/1942212,如需转载请自行联系原作者