標籤:
一、讀寫分離
從庫能進行查詢,這樣可以分擔主庫的大量的查詢請求。
1、先向主庫中插入一條測試資料
[[email protected] bin]# ./mongo --port 28010MongoDB shell version: 1.8.1connecting to: 127.0.0.1:28010/testrs1:PRIMARY> db.c1.insert({age:30})db.c2rs1:PRIMARY> db.c1.find(){ "_id" : ObjectId("4fc77f421137ea4fdb653b4a"), "age" : 30 }
2、在從庫中進行查詢等操作
[[email protected] bin]# ./mongo --port 28011MongoDB shell version: 1.8.1connecting to: 127.0.0.1:28011/testrs1:SECONDARY> show collectionsThu May 31 22:27:17 uncaught exception: error: { "$err" : "not master and slaveok=false","code" : 13435 }rs1:SECONDARY>
查詢報錯,說明是個從庫且不能執行查詢的操作
3、讓從庫可以讀,分擔主庫的壓力
rs1:SECONDARY> db.getMongo().setSlaveOk()not master and slaveok=falsers1:SECONDARY> show collectionsc1system.indexesrs1:SECONDARY> db.c1.find(){ "_id" : ObjectId("4fc77f421137ea4fdb653b4a"), "age" : 30 }rs1:SECONDARY>
我們做到了。
二、容錯移轉
複製集比傳統的Master-Slave 有改進的地方就是他可以進行故障的自動轉移,如果我們停掉複製集中的一個成員,那麼剩餘成員會再自動選舉出一個成員,做為主庫,例如:我們將28010 這個主庫停掉,然後再看一下複製集的狀態
測試:
1、kill 28010連接埠的MongoDB
[[email protected] bin]# ps aux|grep mongodroot 6706 1.6 6.9 463304 6168 Sl 21:49 0:26/Apps/mongo/bin/mongod --replSet rs1 --keyFile /data/key/r0 --fork --port 28010root 6733 0.4 6.7 430528 6044 ? Sl 21:50 0:06/Apps/mongo/bin/mongod --replSet rs1 --keyFile /data/key/r1 --fork --port 28011root 6747 0.4 4.7 431548 4260 ? Sl 21:50 0:06/Apps/mongo/bin/mongod --replSet rs1 --keyFile /data/key/r2 --fork --port 28012root 7019 0.0 0.7 5064 684 pts/2 S+ 22:16 0:00 grep mongod[[email protected] bin]# kill -9 6706
View Code
2、再查看複製集狀態
[[email protected] bin]# ./mongo --port 28011MongoDB shell version: 1.8.1connecting to: 127.0.0.1:28011/testrs1:SECONDARY> rs.status(){"set" : "rs1","date" : ISODate("2012-05-31T14:17:03Z"),"myState" : 2,"members" : [{"_id" : 0,"name" : "localhost:28010","health" : 0,"state" : 1,"stateStr" : "(not reachable/healthy)","uptime" : 0,"optime" : {"t" : 1338472279000,"i" : 1},"optimeDate" : ISODate("2012-05-31T13:51:19Z"),"lastHeartbeat" : ISODate("2012-05-31T14:16:42Z"),"errmsg" : "socket exception"},{"_id" : 1,"name" : "localhost:28011","health" : 1,"state" : 2,"stateStr" : "SECONDARY","optime" : {"t" : 1338472279000,"i" : 1},"optimeDate" : ISODate("2012-05-31T13:51:19Z"),"self" : true},{"_id" : 2,"name" : "localhost:28012","health" : 1,"state" : 1,"stateStr" : "PRIMARY","uptime" : 1528,"optime" : {"t" : 1338472279000,"i" : 1},"optimeDate" : ISODate("2012-05-31T13:51:19Z"),"lastHeartbeat" : ISODate("2012-05-31T14:17:02Z")}],"ok" : 1}rs1:SECONDARY> "stateStr" : "(not reachable/healthy)",View Code
可以看到28010 這個連接埠的MongoDB 出現了異常,而系統自動選舉了28012 這個連接埠為主,所以這樣的故障處理機制,能將系統的穩定性大大提高。
MongoDB整理筆記の管理Replica Sets