Rails、Puma、Postgres:预加载 Active Record 定义?
Rails, Puma, Postgres: Preloading Active Record definitions?
每次启动后,我都会看到对数据库的如下查询:
一旦每个 puma worker 被一个请求击中一次(击中数据库),这些就会消失。这很烦人,因为它可以向一个请求添加 50+ sql 个查询 (1s +)。我想做的是在每次工作人员启动时以某种方式预加载这些。
我试过了
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
这是行不通的。
我都有
config.cache_classes = true
config.eager_load = true
在我的环境中设置。
我希望有某种 rails 设置可以做到这一点 - 在生产中默认情况下似乎是一件明智的事情?
见https://github.com/rails/rails/issues/24133
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
在初始化程序中。
每次启动后,我都会看到对数据库的如下查询:
一旦每个 puma worker 被一个请求击中一次(击中数据库),这些就会消失。这很烦人,因为它可以向一个请求添加 50+ sql 个查询 (1s +)。我想做的是在每次工作人员启动时以某种方式预加载这些。
我试过了
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
这是行不通的。
我都有
config.cache_classes = true
config.eager_load = true
在我的环境中设置。
我希望有某种 rails 设置可以做到这一点 - 在生产中默认情况下似乎是一件明智的事情?
见https://github.com/rails/rails/issues/24133
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
在初始化程序中。