MongoDB文檔資料庫提供了主從複製模式,其實MongoDB的主從複製配置很簡單,就是啟動MongoDB服務進程的時候 分別指定 --master ,--slave,一個是以主模式啟動,另一個屬於從模式啟動,當主庫更新時,資料就會被被複製到從資料庫中。
此次測試僅在單台伺服器上開啟2deamon來類比2台伺服器進行主從複製:
主庫:./mongod --master --dbpath=/opt/monogdata/data --port=60000
從庫:./mongod --slave --dbpath=/opt/monogdata/slavedata/ --port=60010 --source=127.0.0.1:60000
--主庫:
[monogdb@yangDB bin]$ ./mongo --port 60000
MongoDB shell version: 1.8.3-rc0
connecting to: 127.0.0.1:60000/test
> show dbs
admin (empty)
local 1.203125GB
test 0.203125GB
> use test
switched to db test
> show collections --查看主庫中的對象。
system.indexes --system.indexes用來存放索引的表
test--一個測試表
--查看test表中的內容
>db.test.find(); --此操作=select * from test;
{ "_id" : ObjectId("4e3fe5d8e138232e61000000"), "id" : 1, "val" : "hello monogdb" }
--向test表中插入資料
> db.test.insert({id:2,val:"yangql is learing monogdb master slave!"});
> db.test.find();
{ "_id" : ObjectId("4e3fe5d8e138232e61000000"), "id" : 1, "val" : "hello monogdb" }
{ "_id" : ObjectId("4e45291c018d1a0d765a9788"), "id" : 2, "val" : "yangql is learing monogdb master slave!" }
--備庫
[monogdb@yangDB bin]$ ./mongo --port=60010
MongoDB shell version: 1.8.3-rc0
connecting to: 127.0.0.1:60010/test
> db
test
> db.printSlaveReplicationInfo(); ---顯示主庫的資訊。
source: 127.0.0.1:60000
syncedTo: Fri Aug 12 2011 21:19:42 GMT+0800 (CST)
= 7secs ago (0hrs)
> show collections
system.indexes
test --主庫的資料已經被複製到從庫了
> db.test.find();
{ "_id" : ObjectId("4e3fe5d8e138232e61000000"), "id" : 1, "val" : "hello monogdb" }
--主庫更新資料後查看從庫。
> db.test.find();
{ "_id" : ObjectId("4e3fe5d8e138232e61000000"), "id" : 1, "val" : "hello monogdb" }
{ "_id" : ObjectId("4e45291c018d1a0d765a9788"), "id" : 2, "val" : "yangql is learing monogdb master slave!" }
--測試在從庫更新資料,但是不成功!
> db.test.insert({id:2,val:"yangql is writing things to slave,but it can`t do this!"});
not master
> db.test.find();
{ "_id" : ObjectId("4e3fe5d8e138232e61000000"), "id" : 1, "val" : "hello monogdb" }
{ "_id" : ObjectId("4e45291c018d1a0d765a9788"), "id" : 2, "val" : "yangql is learing monogdb master slave!" }
monogdb的主從複製是不能達到主庫當機以後,從庫自動升級到主庫的,而Replica Pairs借用arbiter可以完成主從故障遷移 。