我可以可靠地使连接池大小小于同时使用ActiveRecord连接的线程数吗?我希望线程池大小为一。
我收到错误:
could not obtain a database connection within 5.000
conds (waited 5.000 seconds) ActiveRecord::ConnectionTimeoutError)
我正在尝试模拟我的本地机器。但是我也遇到了同样的错误。
@db_host = "localhost"
@db_user = "root"
@db_pass = "root"
@db_name = "me_dev1"
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => @db_host,
:database => @db_name,
:pool => 1,
:reaping_frequency => 1
)
class Test < ActiveRecord::Base
def create_data
100.times do |i|
t1=Thread.new {
begin
test=Test.where(:test_name => "automation test")
puts test
ensure
ActiveRecord::Base.connection.close if ActiveRecord::Base.connection ;
ActiveRecord::Base.clear_active_connections! ;
end
}
t1.join
end
end
end
Test.new.create_data
谢谢
答案 0 :(得分:1)
ActiveRecord为每个线程使用单独的连接。使此代码工作的可靠方法是使池大小大于或等于线程数。
如果您希望池大小小于线程数,则应增加ActiveRecord等待从池中获取连接的时间。这是通过checkout_timeout
选项完成的,例如:
ActiveRecord::Base.establish_connection(
...
checkout_timeout: 3_600, # wait an hour
)