雖然mongo官方並不推薦在replica set的secondary server上進行查詢操作,但是作為一個mysql的老用戶,表示一定要這樣用。
繼續昨天1主2從1 arbiter的架構。
從ubuntu:27020;rs0;
主ubuntu:27021;rs0;
從ubuntu:27022;rs0;
A ubuntu:27023;rs0;
php腳本在建立連接的時候,應該連接哪個mongo服務器呢?
答案是主從A都隨意。 其實應該是把這四台都寫上才對。
當然在這四台機器前面再加一個proxy就更好了。
接下來的問題,就是如何讓find()等只讀操作route到從服務器了,很容易想到slaveOk()吧?
http://kr1.php.net/manual/en/mongodb.setslaveokay.php
可惜的是, 這個method 被DEPRECATED 了。
替代的辦法就是:
MongoClient::setReadPreference()
http://kr1.php.net/manual/en/mongoclient.setreadpreference.php
而且這個setReadPreference()方法可以應用在 MongoClient,MongoDB,MongoCollection,MongoCursor四個層次上面。只要設置為MongoClient::RP_SECONDARY或者MongoClient::RP_SECONDARY_PREFERRED, find()等只讀操作就會被分發到從服務器。
問題也隨之而來,如何證明setReadPreference()是有效的? 如何證明你的查詢真實發生在每一台secondary服務器?
恩,show processlist :)
db.currentOP()
其實還有更簡單的方法:
http://kr1.php.net/manual/en/class.mongolog.php
各種log看的很爽。
2014-07-01 13:41:02 - REPLSET (FINE): limiting by credentials: done
2014-07-01 13:41:02 - REPLSET (FINE): sorting servers by priority and ping time
2014-07-01 13:41:02 - REPLSET (FINE): - connection: type: SECONDARY, socket: 42, ping: 0, hash: ubuntu:27020;rs0;.;6034
2014-07-01 13:41:02 - REPLSET (FINE): - connection: type: SECONDARY, socket: 42, ping: 0, hash: ubuntu:27022;rs0;.;6034
2014-07-01 13:41:02 - REPLSET (FINE): sorting servers: done
2014-07-01 13:41:02 - REPLSET (FINE): selecting near servers
2014-07-01 13:41:02 - REPLSET (FINE): selecting near servers: nearest is 0ms
2014-07-01 13:41:02 - REPLSET (FINE): - connection: type: SECONDARY, socket: 42, ping: 0, hash: ubuntu:27020;rs0;.;6034
2014-07-01 13:41:02 - REPLSET (FINE): - connection: type: SECONDARY, socket: 42, ping: 0, hash: ubuntu:27022;rs0;.;6034
2014-07-01 13:41:02 - REPLSET (FINE): selecting near server: done
2014-07-01 13:41:02 - REPLSET (INFO): pick server: random element 0
2014-07-01 13:41:02 - REPLSET (INFO): - connection: type: SECONDARY, socket: 42, ping: 0, hash: ubuntu:27020;rs0;.;6034
PS:
isMaster, hostInfo等cmd貌似只會在master上執行。。。