MM 本身并不支持这一点,但通过插件在每个模型的基础上做到这一点并不难。
module MongoMapper
module Plugins
module ReadPreference
extend ActiveSupport::Concern
included do
class << self
attr_accessor :read_preference
end
end
module ClassMethods
def query(options={})
options.merge!(:read => read_preference) if read_preference
super options
end
def with_read_preference(preference)
self.read_preference = preference
begin
yield
ensure
self.read_preference = nil
end
end
end
end
end
end
MongoMapper::Document.plugin(MongoMapper::Plugins::ReadPreference)
并用我的主集群测试它:
2.0.0p0 :002 > User.first
=> <User:0x30a1948 _id: 4cddf1ff98db746691000002, display_name: (Deleted account)>
2.0.0p0 :003 > User.with_read_preference(:secondary) { User.first }
Mongo::ConnectionFailure: No replica set member available for query with read preference matching mode secondary and tags matching [].
有用!
如果您想要对连接进行全局设置,您可以使用模块属性扩展 MongoMapper 模块,并修改插件以首先查找它。