使用连接池处理活动记录超时的正确方法是什么?

Ada*_*dam 14 mysql activerecord multithreading exception-handling ruby-on-rails

我已经跟踪了一个奇怪的错误,undefined method `run_callbacks' for nil:NilClass并且能够使用此示例代码重现它.

基本上问题是活动记录正在超时(默认为5s)但抛出一个未定义的方法异常,这对我来说似乎不对.

但无论如何,处理这个问题的正确方法是什么?在我的真实代码中,我有一堆忙于做实际工作的线程但偶尔会遇到这个错误.所以想象一下,这puts是真正的代码.我希望现有的线程在发生这种情况时继续工作.

threads = []
10.times do |n|

 threads <<  Thread.new {
    ActiveRecord::Base.connection_pool.with_connection do |conn|
      puts "#{n} #{conn}"
      res =  conn.execute("select sleep(6)", :async => true)
    end
  }
end

# block and wait for all threads to finish
threads.each { |t| puts "joined" ; t.join }
rescue Exception => e
  puts  $!, $@
end
Run Code Online (Sandbox Code Playgroud)

如果我按原样运行此代码,我会得到异常.如果我将睡眠减少到4s,我就不会.这是6s睡眠的输出.

joined
0 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c6380>
1 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c5548>
2 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c4fe4>
3 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c4a80>
4 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c451c>
joined
joined
joined
joined
joined
undefined method `run_callbacks' for nil:NilClass
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:212:in `checkin'
sqltst.rb:31:in `join'
sqltst.rb:31
sqltst.rb:31:in `each'
sqltst.rb:31
Run Code Online (Sandbox Code Playgroud)

gsh*_*lin 1

自从这个问题发布以来,ActiveRecord 在这个领域做了很多工作。以下是一些很好的解释:http://bibwild.wordpress.com/2012/03/15/activerecord-concurrency-currently-good-news-and-bad/