Rails / Unicorn before_fork阻止,断开与辅助数据库的连接

时间:2013-01-26 10:50:13

标签: ruby-on-rails ruby heroku unicorn

我们在单独的模型中使用两个数据库,一个主数据库和一个辅助数据库,如下所示:

class SecondModel < ActiveRecord::Base
  establish_connection(ENV['SECOND_DATABASE'])
end

我将在Heroku应用程序上切换到Unicorn,我们必须断开数据库的连接:

before_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
  end
end

我不确定关闭第二个数据库的连接。 有没有人对此有任何想法?

1 个答案:

答案 0 :(得分:2)

好的我觉得我现在正在使用它,这是代码:

before_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    # disconnect primary database
    ActiveRecord::Base.connection.disconnect!
    Rails.logger.info('Disconnected from ActiveRecord')

    # disconnect the second database
    SecondModel.connection.disconnect! if SecondModel.connection.active?
    Rails.logger.info('Disconnected from SecondModel')
  end
end

after_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    # connect primary database
    ActiveRecord::Base.establish_connection
    Rails.logger.info('Connected to ActiveRecord')

    # connect second database
    SecondModel.establish_connection(ENV["SECOND_DATABASE"])
    Rails.logger.info('Connected to SecondModel')

    # verify connections
    ActiveRecord::Base.verify_active_connections!
  end
end

我遇到了一些错误,因为我在重新连接到SecondModel的数据库之前验证了连接。

欢迎任何想法!