在写多读少的应用中,使用Replica Sets来实现读写分离。通过在连接时指定或者在主库指定slaveOk,由Secondary来分担读的压力,Primary只承担写操作。
对于replica set 中的secondary 节点默认是不可读的,
[mongodb@rac4 bin]$ mongo 127.0.0.1:28019
MongoDB shell version: 2.0.1
connecting to: 127.0.0.1:28019/test
SECONDARY>
SECONDARY>
SECONDARY> db.yql.find()
error: { "$err" : "not master and slaveok=false", "code" : 13435 }
SECONDARY> db.getMongo()
connection to 127.0.0.1:28019
SECONDARY> db.getMongo().setSlaveOk();
not master and slaveok=false
在主库上设置 slaveok=ok
[mongodb@rac4 bin]$ mongo 127.0.0.1:28018
MongoDB shell version: 2.0.1
connecting to: 127.0.0.1:28019/test
PRIMARY> db.getMongo().setSlaveOk();
PRIMARY>
在备库进行测试
SECONDARY> db.yql.find()
{ "_id" : ObjectId("4eb68b1540643e10a0000000"), "age" : 29, "id" : 0, "name" : "2" }
{ "_id" : ObjectId("4eb68b1540643e10a0000001"), "age" : 77, "id" : 1, "name" : "h5gfx6r6sz" }
{ "_id" : ObjectId("4eb68b1540643e10a0000002"), "age" : 12, "id" : 2, "name" : "lmj7w6uqanvntaco" }
{ "_id" : ObjectId("4eb68b1540643e10a0000003"), "age" : 56, "id" : 3, "name" : "1ifd3bmzguuv" }
{ "_id" : ObjectId("4eb68b1540643e10a0000004"), "age" : 33, "id" : 4, "name" : "ba0hchjhi2c16" }
{ "_id" : ObjectId("4eb68b1540643e10a0000005"), "age" : 70, "id" : 5, "name" : "fe6su2p3t2gdckt" }
{ "_id" : ObjectId("4eb68b1540643e10a0000006"), "age" : 57, "id" : 6, "name" : "cq" }
{ "_id" : ObjectId("4eb68b1540643e10a0000007"), "age" : 75, "id" : 7, "name" : "0j43jsovjmyvct" }
{ "_id" : ObjectId("4eb68b1540643e10a0000008"), "age" : 60, "id" : 8, "name" : "eusg4aa5a6ke64zf5ye7" }
{ "_id" : ObjectId("4eb68b1540643e10a0000009"), "age" : 40, "id" : 9, "name" : "iwzcrdjcpoc8f" }
{ "_id" : ObjectId("4eb68b1540643e10a000000a"), "age" : 59, "id" : 10, "name" : "er3iemdl" }
{ "_id" : ObjectId("4eb68b1540643e10a000000b"), "age" : 18, "id" : 11, "name" : "dnvz0u" }
{ "_id" : ObjectId("4eb68b1540643e10a000000c"), "age" : 5, "id" : 12, "name" : "n6ac2ad58fk88if02s" }
{ "_id" : ObjectId("4eb68b1540643e10a000000d"), "age" : 4, "id" : 13, "name" : "mob61x3oj0us" }
{ "_id" : ObjectId("4eb68b1540643e10a000000e"), "age" : 32, "id" : 14, "name" : "1ylc0" }
{ "_id" : ObjectId("4eb68b1540643e10a000000f"), "age" : 18, "id" : 15, "name" : "nbl9r0dnd0vmi" }
{ "_id" : ObjectId("4eb68b1540643e10a0000010"), "age" : 114, "id" : 16, "name" : "gfzc02j7npkv25" }
{ "_id" : ObjectId("4eb68b1540643e10a0000011"), "age" : 34, "id" : 17, "name" : "ac8kfl8" }
{ "_id" : ObjectId("4eb68b1540643e10a0000012"), "age" : 9, "id" : 18, "name" : "wtpqii0dh" }
{ "_id" : ObjectId("4eb68b1540643e10a0000013"), "age" : 81, "id" : 19, "name" : "xi7r4ej" }
has more
这样就可以实现读写分离操作了。