在死线程上关闭ActiveRecord连接

时间:2013-04-30 20:49:59

标签: activerecord rails-activerecord

如果一个线程死了或者我必须杀死一个使用ActiveRecord连接的线程,我该如何确保将ActiveRecord连接返回给池?我一直遇到像

这样的错误

DEPRECATION WARNING: Database connections will not be closed automatically, please close your database connection at the end of the thread by calling关闭on your connection. For example: ActiveRecord::Base.connection.close

但是如何确保在意外死亡的线程上或者调用Thread.kill的线程上发生这种情况?

1 个答案:

答案 0 :(得分:3)

确保连接关闭=)

Thread.new do
  begin
     raise "foo"
  ensure
     begin
        if (ActiveRecord::Base.connection && ActiveRecord::Base.connection.active?)
           ActiveRecord::Base.connection.close
        end
      rescue
      end
  end
end