Active Record mySQL Timeout ERROR -- : worker=0 PID:(xxxxx) timeout (61s > 60s), killing

Active Record mySQL Timeout ERROR -- : worker=0 PID:(xxxxx) timeout (61s > 60s), killing

我的控制器上有一个异步操作,可以根据用户输入执行繁重的 SQL 查询。

  @results = ActiveRecord::Base
  .connection
  .select_all(query_string)
  .map do |record|
    Hashie::Mash.new(record)
  end

发生这种情况时,我从服务器得到的唯一响应是

E, [2020-02-05T16:14:04.133233 #59909] ERROR -- : worker=0 PID:60952 timeout (61s > 60s), killing
E, [2020-02-05T16:14:04.159372 #59909] ERROR -- : reaped #<Process::Status: pid 60952 SIGKILL (signal 9)> worker=0

有什么方法可以在后端捕获此超时,以便为用户提供正确的反馈?

尝试使用 Timeout::timeout(x) 但没有成功。

您可以自己添加另一个更短的超时,并在工作人员被杀死之前处理这种情况。这样的事情可能是一个好的开始:

require 'timeout'

begin
  # 5 seconds before the MySQL timeout would kick in
  Timeout.timeout(55) do
    # have only the slow query in this block
    @database_results = ActiveRecord::Base.connection.select_all(query_string)
  end
rescue Timeout::Error
  # Handle the timeout. Proper error handling depends on your application.
  # In a controller you might just want to return an error page, in a 
  # background worker you might want to record the error in your database.
end

# time to translate the data should not count towards the timeout
@results = @database_results.map  { |r| Hashie::Mash.new(r) }