2014-10-02 62 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

相關問題