2013-07-21 2 views
1

기본 데이터 스토어에 MongoMapper를 사용하고 있으며 기본 복제본이 아닌 복제본 세트의 슬레이브 노드에 대해보고 작업을 실행하고 싶습니다. 불행히도, 우리의 백그라운드 작업의 대부분은 읽기/쓰기이며 기본 작업에 반대해야합니다. 일시적으로 MongoMapper가 슬레이브 복제본에서 읽을 수 있도록 전환합니다.

인가가 나는 다음과 같은 것을 할 수있는 몇 가지 방법 : 지금 MongoMapper이 정말 그 후 변경하지 다음 연결을 가져으로 선호도를 읽을 설정을 원하고 것 같습니다

MongoMapper.options({:slave_ok => true}) 

report.fetch_data # does all sorts of stuff, uses normal Models, developer doesn't have to go out of his/her way to specify a read preference 

MongoMapper.options({:slave_ok => force}) 

을 .

답변

3

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 모듈을 모듈 속성으로 확장하고 플러그인을 수정하여 먼저 찾도록 할 수 있습니다.

+0

전 모델을 살펴보고 수동으로 연결을 바꿔주는 것보다 (글로벌 설정에 대해 언급하면) 훨씬 더 깨끗합니다. 감사! – edebill

+1

스레딩을주의하십시오 (예 : 백그라운드 작업이 sidekiq를 사용하는 경우) –

+0

확실히; 클래스 속성에 상태를 유지할 때마다 스레딩이 문제가됩니다. –

관련 문제