我在AWS RDS下有一个带有多区域架构的Postgres数据库的Rails应用程序。 RDS使用的HA架构是主/从,它们为服务提供指向当前主站的单个端点。
每当发生数据库故障转移时,Active Record将继续尝试连接到同一服务器,而不是重试连接以获取主服务器的新IP。
有没有办法创建一个"全球"救助只运行ActiveRecord::StatementInvalid: PG::ConnectionBad: PQsocket() can't get socket descriptor
的{{1}}错误会使下一个查询生效吗?
答案 0 :(得分:2)
通过将猴子补丁应用到postgres_adapter
,我能够在故障转移事件后重新连接Active Record。
lib/core_ext/active_record/postgresql_adapter.rb
:
require 'active_record/connection_adapters/postgresql_adapter'
class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
private
def exec_no_cache(sql, name, binds)
log(sql, name, binds) { @connection.async_exec(sql, []) }
rescue ActiveRecord::StatementInvalid => e
if e.to_s.include?('PG::ConnectionBad')
ActiveRecord::Base.connection_pool.disconnect!
end
raise e
end
end