ActiveRecord::ConnectionTimeoutError happening sporadically

一世执手 提交于 2019-11-29 16:31:42

问题


Whenever I have an application using ActiveRecord I get this ConnectionTimeoutError - but always after a certain unknown period of time

ActiveRecord::ConnectionTimeoutError (could not obtain a database connection within 5 seconds.  The max pool size is currently 30; consider increasing it.):

It was previously set to 5, we have already increased it, and there is no way it can be using 30 connections at the same time. The only thing we use ActiveRecord for is our session store.

Our database.yml file looks like:

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 30
  timeout: 5000

(Test and production settings are the same)


I have been googling this occurrence, and just came across this posting:

https://groups.google.com/forum/#!msg/copenhagen-ruby-user-group/GEHgi_WudmM/gnCiwWqmVfMJ

Which mentions that ActiveRecord does not check a connection back into the pool once it is done with it?? Is that true? Do I need to manually manage the connections?

I appreciate any advice!!

edit I should probably mention I am running Rails 3.1.3


回答1:


Rails has a middleware called ActiveRecord::ConnectionAdapters::ConnectionManagement which clears active connections every request so they do not stick around. Check your middleware to make sure you have this (which is there by default), run "rake middleware". You should not have to manage the connections manually to answer your last question.

Run this in your console

   ActiveRecord::Base.clear_active_connections!



回答2:


I used this code on my Sinatra app

after do
  ActiveRecord::Base.clear_active_connections!
end   

This solve my problem




回答3:


Applies also to Rails 5, since Puma is default server.

If you are using Threaded Servers like Puma, Phushion Passenger, they create multiple threads of the same application. Thereby making your application run faster, by concurrently executing each incoming requests.

Make sure that the pool size is equal or more than the number of threads. I was having an issue when few of my threads were giving me ActiveRecord::ConnectionTimeoutError, and the problem was vague since it occurs once in a while not very often.




回答4:


I was also experiencing a similar problem with a Sinatra App, I added

after do
  ActiveRecord::Base.clear_active_connections!
end 

To my application controller and it solved my problem.

This construct is known as a filter and it evaluates after each request.

I'm not sure what was actually happening with the application, but I would suspect that connections weren't being closed after each request.



来源:https://stackoverflow.com/questions/12045495/activerecordconnectiontimeouterror-happening-sporadically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!