2017-02-17 1 views
0

우리의 앱은 모든 응용 프로그램 요청 (읽기 및 쓰기)이 마스터 DB로가는 Unicorn과 마스터 - 슬레이브 데이터베이스 구성으로 Heroku에 배포됩니다.레일에서 읽기 전용 데이터베이스에 액세스하는 가장 좋은 방법

read 트래픽 중 일부를 수신자 (슬레이브) 데이터베이스로 리디렉션해야합니다.

이를 달성하기 위해, 우리는 read_only_database_connection.rb 추가 -

class ReadOnlyDatabaseConnection < ActiveRecord::Base 
    self.abstract_class = true 
end 

을하고 믹스 인을 추가 switch_connection.rb

module SwitchConnection 
    def readonly_db_connection  
    current_conf = ReadOnlyDatabaseConnection.connection_config 
    begin 
     ReadOnlyDatabaseConnection.establish_connection(READONLY_CONFIG).tap do 
     puts "Primary DB -> Follower DB" 
     end 

     yield 
    ensure 
     ReadOnlyDatabaseConnection.establish_connection(current_conf).tap do 
     puts "Follower DB -> Primary DB" 
     end 
    end 
    end 
end 

그리고 application_controller.rb에, 내가 그랬어 -

include SwitchConnection 
around_filter :readonly_db_connection, only: [:index, :show] 

이 권리인가 이 일을하는 방법? 모든 showindex 트래픽을 읽기 전용 데이터베이스로 리디렉션하는 더 좋거나 더 안전한 방법이 있습니까?

+0

이것을 확인하십시오 : https://github.com/thiagopradi/octopus –

답변

0

ActiveRecord::Base에서 상속받은 개체는 데이터베이스를 처리해야합니다. 읽기 전용 슬레이브 데이터베이스를 검사하는 모델을 가질 수 있습니다. 같은 테이블 이름 (나는 당신이 생각하는) 사용하려면

class ReadOnlyModel < ActiveRecord::Base 
    establish_connection 'readonly_db' 

    def readonly? 
    true 
    end 
end 

class Controller 
    def index 
    @models = ReadOnlyModel.all 
    end 
end 

# in config/database.yml 
readonly_database: 
    adapter: #... 

, 당신은 table_name 방법을 사용할 수 있습니다.

class Model < ActiveRecord::Base 
end 

class ReadOnlyModel < ActiveRecord::Base 
    self.table_name :models 
end 

다음은 readonly? 방법에 대한 documentation입니다.

+0

답장을 보내 주셔서 감사합니다. 나는 100 개 이상의 모델을 가지고 있고 그것들을 읽기 전용 모델로 복제하고 싶지는 않습니다. – varunvlalan

관련 문제