简体   繁体   English

Rails,Puma,Postgres:预加载Active Record定义吗?

[英]Rails, Puma, Postgres: Preloading Active Record definitions?

After every boot, I see queries like these to the database: 每次启动后,我都会看到对数据库的查询如下:

在此处输入图片说明

Once each puma worker is hit once with a request (that hits the database), these go away. 一旦每个puma工作者都被请求打了一次(打了数据库),这些请求就消失了。 It's annoying because it can add 50+ sql queries to a request (1s +). 这很烦人,因为它可以向请求(1s +)添加50多个sql查询。 What I want to do is somehow preload these every time a worker boots. 我想做的是每当工人启动时以某种方式预加载这些。

I've tried 我试过了

on_worker_boot do
  ActiveSupport.on_load(:active_record) do
    ActiveRecord::Base.establish_connection
  end
  Rails.application.eager_load!
  ::Rails::Engine.subclasses.map(&:instance).each { |engine| engine.eager_load! }
  ActiveRecord::Base.descendants
end

Which does not work. 哪个不起作用。

I have both 我都有

  config.cache_classes = true
  config.eager_load = true

set in my environment. 在我的环境中设置。

I'm expecting there to be some sort of rails setting that does this - seems like a smart thing to do by default in production? 我期望可以做到这一点-在生产中默认情况下看起来很聪明吗?

See https://github.com/rails/rails/issues/24133 参见https://github.com/rails/rails/issues/24133

Rails 5 will have improvements, but you still currently need to do: Rails 5将进行改进,但是您目前仍需要执行以下操作:

# https://github.com/rails/rails/issues/24133
ActiveSupport.on_load(:active_record) do
  con = ActiveRecord::Base.connection
  filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")

  con.schema_cache.clear!
  con.data_sources.each { |table| con.schema_cache.add(table) }
  open(filename, 'wb') { |f| f.write(Marshal.dump(con.schema_cache)) }
end

in an initializer. 在初始化器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM