MongoDB的主从复制其实很简单,就是在运行主的服务器上开启mongod进程时,加入参数--master即可,在运行从的服务器上开启mongod进程时,加入--slave 和 --source 指定主即可,这样,在主数据库更新时,数据被复制到从数据库中
(这里日志文件和访问数据时授权用户暂时不考虑)
下面我在单台服务器上开启2deamon来模拟2台服务器进行主从复制:
$ mkdir m_master m_slave
$mongodb/bin/mongod --port 28018 --dbpath ~/m_master --master &
$mongodb/bin/mongod --port 28019 --dbpath ~/m_slave --slave --source localhost:28018 &
$mongodb/bin/mongod --port 28018 --dbpath ~/m_master --master &
$mongodb/bin/mongod --port 28019 --dbpath ~/m_slave --slave --source localhost:28018 &
这样主从服务器都已经启动了,可以利用netstat -an -t 查看28018、28019端口是否开放
登录主服务器:
$ mongodb/bin/mongo --port 28018
MongoDB shell version: 1.2.4-
url: test
connecting to: 127.0.0.1:28018/test
type "help" for help
> show dbs
admin
local
test
> use test
switched to db test
> show collections
MongoDB shell version: 1.2.4-
url: test
connecting to: 127.0.0.1:28018/test
type "help" for help
> show dbs
admin
local
test
> use test
switched to db test
> show collections
这里主上的test数据什么表都没有,为空,查看从服务器同样也是这样
$ mongodb/bin/mongo --port 28019
MongoDB shell version: 1.2.4-
url: test
connecting to: 127.0.0.1:28019/test
type "help" for help
> show dbs
admin
local
test
> use test
switched to db test
> show collections
MongoDB shell version: 1.2.4-
url: test
connecting to: 127.0.0.1:28019/test
type "help" for help
> show dbs
admin
local
test
> use test
switched to db test
> show collections
那么现在我们来验证主从数据是否会像想象的那样同步呢?
我们在主上新建表user
> db
test
>db.createCollection("user");
> show collections
system.indexes
user
>
test
>db.createCollection("user");
> show collections
system.indexes
user
>
表user已经存在了,而且test库中还多了一个system.indexes用来存放索引的表
到从服务器上查看test库:
> db
test
> show collections
system.indexes
User
> db.user.find();
>
test
> show collections
system.indexes
User
> db.user.find();
>
从服务器的test库中user表已经存在,同时我还查了一下user表为空
现在我们再来测试一下,向主服务器test库的user表中插入一条数据
> show collections
system.indexes
user
> db.user.insert({uid:1,name:"Falcon.C",age:25});
> db.user.find();
{ "_id" : ObjectId("4b8226a997521a578b7aea38"), "uid" : 1, "name" : "Falcon.C", "age" : 25 }
>
system.indexes
user
> db.user.insert({uid:1,name:"Falcon.C",age:25});
> db.user.find();
{ "_id" : ObjectId("4b8226a997521a578b7aea38"), "uid" : 1, "name" : "Falcon.C", "age" : 25 }
>
这时我们查看从服务器的test库user表时会多出一条记录
来:
> db.user.find();
{ "_id" : ObjectId("4b8226a997521a578b7aea38"), "uid" : 1, "name" : "Falcon.C", "age" : 25 }
>
{ "_id" : ObjectId("4b8226a997521a578b7aea38"), "uid" : 1, "name" : "Falcon.C", "age" : 25 }
>
MongoDB还有 Replica Pairs 和 Master - Master