【问题标题】:ActiveRecord: how to reconnect to PostgreSQL automatically when connection drops?ActiveRecord:连接断开时如何自动重新连接到 PostgreSQL?
【发布时间】:2014-11-27 17:29:41
【问题描述】:

我正在将 ActiveRecord 与 Sinatra 和 PostgreSQL 一起使用。当数据库连接断开时(由于临时网络故障或 postgres 服务器重新启动),我的应用程序不会自动重新获取连接。我必须重新启动应用程序才能再次连接到 postgres。我记得我在另一个项目中使用 Rails 时没有遇到这个问题。

我是否需要放置一些配置或代码来告诉 ActiveRecord 自动重新连接到 PostgreSQL?

【问题讨论】:

    标签: ruby postgresql activerecord sinatra


    【解决方案1】:

    ActiveRecord::Base.verify_active_connections! 已于 2012 年在 rails commit 9d1f1b1ea9e5d637984fda4f276db77ffd1dbdcb 中删除。所以我们不能使用那个方法。

    下面的句子是我简短调查的结果。我不是rails activerecord的专家。所以要小心听。 (但希望这有帮助)

    comment in connection_pool.rb

      # 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
      #    earlier (pre-connection-pooling). Eventually, when you're done with
      #    the connection(s) and wish it to be returned to the pool, you call
      #    ActiveRecord::Base.clear_active_connections!. This will be the
      #    default behavior for Active Record when used in conjunction with
      #    Action Pack's request handling cycle.
    

    所以也许你(和我。我和你有同样的情况)必须将连接返回到池。

    如果要将连接返回到 sinatra 中的池为 Action Pack's request handling cycle,请使用 ActiveRecord::ConnectionAdapters::ConnectionManagement

    use ActiveRecord::ConnectionAdapters::ConnectionManagement
    

    然后如 rails commit 9d1f1b1ea9e5d637984fda4f276db77ffd1dbdcb 中所述,我们使用 a different waythis line 一样,在使用 Basae.connection 时始终遵循操作包生命周期checkout_and_verify

      def connection
        # this is correctly done double-checked locking
        # (ThreadSafe::Cache's lookups have volatile semantics)
        @reserved_connections[current_connection_id] || synchronize do
          @reserved_connections[current_connection_id] ||= checkout
        end
      end
    

    【讨论】:

      【解决方案2】:

      更新 2019-01-11 从 Rails 4.2 开始,我必须使用

      ActiveRecord::Base.clear_active_connections!
      

      并且 ActiveRecord 将在下一次查询时重新连接。也可以在 Rails 控制台上使用,相当方便

      【讨论】:

        【解决方案3】:

        来自https://www.new-bamboo.co.uk/blog/2010/04/11/automatic-reconnection-of-mysql-connections-in-active-record/

        如果您在 Rails 之外或至少在控制器操作之外使用 Active Record,您必须在执行数据库语句之前自行验证连接。这可以通过以下代码完成:

        ActiveRecord::Base.verify_active_connections!
        

        由于 Active Record 每个线程使用一个连接,因此在多线程应用程序中,必须为每个线程单独执行此验证。

        这篇博文是关于重新连接到 MySQL 的,但我猜无论使用什么引擎,它都是一样的,因为它被抽象掉了。该博客还提到了配置中的重新连接选项,但您必须确定这是否适用于 Postgres。

        【讨论】:

        • 我的症状完全一样。但是ActiveRecord::Base.verify_active_connections! 与 rails commit 9d1f1b1e 一起消失了。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        • 2012-08-07
        • 2010-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多