2014-10-02 121 views
2

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

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

回答

0

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

如果您使用Rails的外面活动记录或者您有执行数据库语句之前来验证自己的连接至少外控制器动作。这可以用下面的代码来完成:

ActiveRecord::Base.verify_active_connections! 

由于活动记录使用每线程一个连接,在多线程应用此验证,必须针对每个线程独立地执行。

博客文章是关于重新连接到MySQL,但我猜这将是相同的,无论使用的引擎,因为它被抽象掉。该博客还提到了配置中的重新连接选项,但您必须查明该功能是否适用于Postgres。

+0

我有完全相同的症状。但是'ActiveRecord :: Base.verify_active_connections!'随着rails commit 9d1f1b1e消失了。 – ruseel 2015-11-10 03:34:05

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 

,然后在轨道规定提交我们使用a different waythis line,总是checkout_and_verify 9d1f1b1ea9e5d637984fda4f276db77ffd1dbdcb使用时Basae.connection服从行动包生命周期。

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 
+0

真的很好的答案,很高兴你把这个整理出来! – iain 2015-11-10 09:16:26

相关问题