有没有办法在不通过 http 请求调用实际页面的情况下预先构建页面缓存?
我查看了类似 this 的解决方案和 this ,但这些不会生成缓存。
我有一个相对复杂的 View ,并且想要缓存整个内容。我想在应用程序中预先构建这个缓存版本,这样当用户实际点击它时,它就已经存在了。
谢谢
最佳答案
我们需要从 rake 任务中做一些类似的事情——我们有一个部分需要显示很长的实体列表(~700),这些实体在某种程度上是特定于上下文的,并且由于一系列数据库结构问题和自定义排序标准,在进入缓存之前,第一次渲染很容易花费 > 25 秒> 这通常会超时,因为我们的 HTTP 服务器被设置为在 30 秒后终止 HTTP 请求,并且预缓存此自定义列表是一个办法。
您需要做的是创建 ActiveController::Base 的实例,或者如果您需要辅助方法或其他实体,则创建一个 Controller 的实例,然后将其 lookup_context 引用传递给 ActionView.Renderer 的新实例。
在我们的 rake 任务中,我们执行了以下操作
namespace :rake_for_time_consuming_nonsense do
task :pre_cache_long_list do
PreCacher.pre_fetch_partials
end
end
class PreCacher
def self.pre_fetch_partials
the_controller = ActionController::Base.new
# Set any instance variables required by your partial in the controller,
# they will be passed to the partial with the view_context reference
the_controller.instance_variable_set "@cache_key", cache_key
the_controller.instance_variable_set "@the_object", MyModel.first
view_renderer = ActionView::Renderer.new the_controller.lookup_context
view_renderer.render the_controller.view_context, {partial: 'my_model/the_partial', layout: false}
end
end
这适用于 Rails 3.2.13。
关于ruby-on-rails - 在 Rails 中预构建 View 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6836867/