我们的应用程序部署在 Heroku 上,具有 Unicorn 和主从数据库配置,所有应用程序请求(读取和写入)都转到主数据库。
我们需要的是将一些read
流量重定向到follower(从属)数据库。
为了实现这一点,我们添加了 read_only_database_connection.rb
-
class ReadOnlyDatabaseConnection < ActiveRecord::Base
self.abstract_class = true
end
并添加了一个 mixin 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
流量重定向到只读数据库?
最佳答案
我认为继承自 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
这是 documentation对于 readonly?
方法。
关于ruby-on-rails - 在 Rails 中访问只读数据库的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42302020/