我已经找到了一个奇怪的错误undefined method `run_callbacks' for nil:NilClass
,并且能够使用此示例代码重现它。
基本上问题是活动记录正在超时(默认为5秒)但抛出一个未定义的方法异常,这对我来说似乎不对。
但无论如何,处理这个问题的正确方法是什么?在我的真实代码中,我有一堆忙于做实际工作的线程但偶尔会遇到这个错误。所以想象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
如果我按原样运行此代码,我会得到异常。如果我将睡眠减少到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
答案 0 :(得分:1)
自从发布此问题以来,ActiveRecord已经在这个领域做了很多工作。以下是一些很好的解释:http://bibwild.wordpress.com/2012/03/15/activerecord-concurrency-currently-good-news-and-bad/
答案 1 :(得分:0)
您应该在database.yml中设置pool:10。好像你已达到极限。