我正在使用Sinatra和PostgreSQL的ActiveRecord。当数据库连接中断(由于暂时的网络故障或postgres服务器重新启动)时,我的应用程序不会自动重新获取连接。我必须重新启动应用程序才能再次连接到Postgres。我记得在另一个项目中使用Rails时没有这个问题。我需要添加一些配置或代码来告诉ActiveRecord自动重新连接到PostgreSQL吗?
ActiveRecord::Base.verify_active_connections!
在2012年的rails提交9d1f1b1ea9e5d637984fda4f276db77ffd1dbdcb中已被删除,因此我们无法使用该方法。
以下句子是我进行短暂调查的结果。我不是Rails ActiveRecord方面的专家,所以请谨慎听取。(但希望这会有所帮助)
# 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的请求处理周期
一样处理,请使用ActiveRecord :: ConnectionAdapters :: ConnectionManagement。
use ActiveRecord::ConnectionAdapters::ConnectionManagement
根据rails提交9d1f1b1ea9e5d637984fda4f276db77ffd1dbdcb所述,我们正在使用此行中的不同方式
,当使用Basae.connection
时,始终通过遵守Action Pack生命周期来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
更新于2019年01月11日,从Rails 4.2开始,我必须使用
ActiveRecord::Base.clear_active_connections!
并且ActiveRecord会在下一次查询时重新连接。这也适用于Rails控制台,非常方便。
如果您在Rails之外使用Active Record,或者至少在控制器操作之外使用它,您必须在执行数据库语句之前自行验证连接。可以使用以下代码完成此操作:
ActiveRecord::Base.verify_active_connections!
ActiveRecord::Base.verify_active_connections!
已经在Rails提交9d1f1b1e中消失了。 - ruseel