我在rails应用程序上遇到了一些错误,其中包括:
ActiveRecord::StatementInvalid: Mysql::Error: Lost connection to MySQL server during query: SELECT * FROM `actions` WHERE (`foo`.`id` = 16)
Run Code Online (Sandbox Code Playgroud)
似乎正在发生的事情是mysql连接在超时后被关闭,并且rails没有注意到它为时已晚.
我找到 的补救措施似乎是在database.yaml中将reconnect标志设置为true,或者对于添加一些代码的任何数据库操作:
def some_database_operation
begin
Account.find(1)
# or some other database operations here...
rescue ActiveRecord::StatementInvalid
ActiveRecord::Base.connection.reconnect!
unless @already_retried
@already_retried = true
retry
end
raise
else
@already_retried = false
end
end
end
Run Code Online (Sandbox Code Playgroud)
我在此处列出了此选项,因为此选项显然对交易不安全:
ActiveRecord::ConnectionAdapters::MysqlAdapter.module_eval do
def execute_with_retry_once(sql, name = nil)
retried = false
begin
execute_without_retry_once(sql, name)
rescue ActiveRecord::StatementInvalid => exception
ActiveRecord::Base.logger.info "#{exception}, retried? #{retried}"
# Our database …Run Code Online (Sandbox Code Playgroud) 如何在Rails应用程序中强制MySQL重新连接?我想定期或在数据库异常,如"MySQL服务器已经消失"这样做.
我发现ActiveRecord::Base.remove_connection但是在编写时,它应该被称为某个模型,而不是整个应用程序.