Ruby activerecord 线程中使用遇到 DEPRECATION WARNING

Louis · 2013年04月05日 · 最后由 seoaqua 回复于 2014年01月21日 · 3139 次阅读

如题。 程序中使用到了 rufus/scheduler。

代码是这样的:

def run
   # db operation
    threads << Thread.new(keyword) do |k|
      # db operation
    end
end

def db(&block)
    begin 
        Connection::Weibowarning.conn
        yield
    rescue =>ex     
        raise ex
    ensure
        ActiveRecord::Base.connection.close
    end
end

scheduler.every '60s' do
    db { run }
end

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

我试过在 run 方法中的两个 db operation 前后分别连接和关闭,但是也会提示这个错。

请问该怎么解决呢?

不用管..按照他说的做

#1 楼 @jjym 我照他说的 close 了,但是还是报。

#2 楼 @Louis 报下无所谓..

多线程环境下不是 close 连接,应该是把连接归还连接池,试试改成

ActiveRecord::Base.clear_active_connections!

#2 楼 @Louis #4 楼 @robbin 我也遇到这个问题了,大家解决了吗?

#4 楼 @robbin
解决方法是

ActiveRecord::Base.connection_pool.with_connection do 
  #do something
end

https://github.com/rails/rails/issues/5330

需要 登录 后方可回复, 如果你还没有账号请 注册新账号