私たちのアプリは、すべてのアプリリクエスト(読み書き)がマスター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]
は、これは正しいですこれを行う方法? show
とindex
のすべてのトラフィックをreadonlyデータベースにリダイレクトするためのより良いまたはより安全なアプローチはありますか?
これをチェックしてください:https://github.com/thiagopradi/octopus –