如何自动重新连接 Rails 6 PostgreSQL 连接?

Ale*_*pin 7 ruby postgresql ruby-on-rails

我有一个带有一些工作进程的 Rails 6 应用程序。该应用程序使用 PostgreSQL 作为数据库。有时数据库会重新启动(例如次要版本升级)并且工作人员会失去连接。我希望他们能够自动重新连接,但它没有发生。

我尝试reconnect: true在database.yml中使用标志。同样的故事。我仍然收到PG::UnableToSend: no connection to the server该选项甚至在PostgresqlAdapter中不可用。我猜这只是 MySQL 适配器选项。

工作人员是我运行的简单服务类rails runner

可以做什么?我相信答案一定很简单。

Ale*_*pin 9

我为PG自动重连做了一个ActiveRecord补丁。

处理异常的工作可以优化,但我有一些奇怪的PG::UnableToSend,PG::ConnectionBad和混合PG::Error,所以我比较异常名称。

module PostgreSQLAdapterAutoReconnectPatch
  QUERY_EXCEPTIONS = [
    "SSL connection has been closed unexpectedly",
    "server closed the connection unexpectedly",
    "no connection to the server",
  ].freeze

  CONNECTION_EXCEPTIONS = [
    "could not connect to server",
    "the database system is starting up",
  ].freeze

  def exec_query(*args)
    super(*args)
  rescue ActiveRecord::StatementInvalid => e
    raise unless recoverable_query?(e.message)

    in_transaction = transaction_manager.current_transaction.open?
    try_reconnect
    in_transaction ? raise : retry
  end

  private

  def recoverable_query?(error_message)
    QUERY_EXCEPTIONS.any? { |e| error_message.include?(e) }
  end

  def recoverable_connection?(error_message)
    CONNECTION_EXCEPTIONS.any? { |e| error_message.include?(e) }
  end

  def try_reconnect
    sleep_times = [0.1, 0.5, 1, 2, 4, 8, 16, 32]

    begin
      reconnect!
    rescue PG::Error => e
      sleep_time = sleep_times.shift
      if sleep_time && recoverable_connection?(e.message)
        logger.warn("DB Server timed out, retrying in #{sleep_time} sec")
        sleep sleep_time
        retry
      else
        logger.error(e)
        raise
      end
    end
  end
end

require "active_record/connection_adapters/postgresql_adapter"
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend(PostgreSQLAdapterAutoReconnectPatch)
Run Code Online (Sandbox Code Playgroud)

灵感来自