新手问题 ActiveRecord 在 DB 服务中止重启后,无法自动重连

linjunzhugg · 2018年11月15日 · 最后由 linjunzhugg 回复于 2018年12月26日 · 1861 次阅读

纯 Ruby 项目,用了 ActiveRecord-4.2 来管理数据库,数据库为 PG。

该项目会启动成为一个常驻进程,运行过程中,发现 PG 数据库一旦中止,重启后,ActiveRecord 不会自动去重连数据库,因而一直报无法连接的错误,不知道有没人 遇到过?搜索了好一阵子还是没搜到解决方案。

PG 为啥要重启

module ActiveRecord::ConnectionAdapters
  class Mysql2Adapter
    alias_method :execute_without_retry, :execute

    def execute(*args)
      execute_without_retry(*args)
    rescue ActiveRecord::StatementInvalid => e
      err_msg = e.message
      if err_msg =~ /has gone away/ || err_msg =~ /Lost connection/
        logger.debug("#{Time.current.to_s(:db)}---#{err_msg}")
        reconnect!
        retry
      else
        raise e
      end
    end
  end
end
ruby_sky 回复

这种方式要判断当前连接是否处于事务中,重连后原连接持有的锁等信息会被丢掉,如果应用程序还在按照事务进行操作的话可能会出问题。 https://dalibornasevic.com/posts/77-auto-reconnect-for-activerecord-connections,建议楼主参考这个。

reconnect: true,了解一下。。。

production:
  adapter: mysql2
  encoding: utf8mb4
  collation: utf8mb4_unicode_ci
  database: oa_production
  username: deployer
  reconnect: true
ericguo 回复

抱歉一个月后才看到回复。

reconnect 这个属性只适用于 mysql,pg 是不支持该属性的

early 回复

我也有看到这篇文章,哈哈

只是这个方式也只是适用于 mysql , pg 的 adapter 不支持这个参数

需要 登录 后方可回复, 如果你还没有账号请 注册新账号