Rails, Mongoid & Unicorn config for Heroku

2019-03-22 15:03发布

问题:

I am using Mongoid 3, with Rails 3.2.9 and Unicorn for production. Would like to setup a before_fork & after_fork for the connection to mongodb, found the following code for active record:

before_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
    Rails.logger.info('Disconnected from ActiveRecord')
  end
end

after_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
    Rails.logger.info('Connected to ActiveRecord')
  end
end

What is the relevant code for Mongoid (to connect and disconnect)?

Update:

You dont actually need to do this, so for people coming to view this question see:

http://mongoid.org/en/mongoid/docs/rails.html

"Unicorn and Passenger

When using Unicorn or Passenger, each time a child process is forked when using app preloading or smart spawning, Mongoid will automatically reconnect to the master database. If you are doing this in your application manually you may remove your code."

Though it would still be interesting to know what would be the equivalent Mongoid code.

回答1:

You dont actually need to do this, so for people coming to view this question see:

http://mongoid.org/en/mongoid/docs/rails.html

"Unicorn and Passenger

When using Unicorn or Passenger, each time a child process is forked when using app preloading or smart spawning, Mongoid will automatically reconnect to the master database. If you are doing this in your application manually you may remove your code."

Though it would still be interesting to know what would be the equivalent Mongoid code.



回答2:

What about ::Mongoid.default_session.connect ::Mongoid.default_session.disconnect