ruby-on-rails - 在 Rails 中预构建 View 缓存

标签 ruby-on-rails caching

有没有办法在不通过 h​​ttp 请求调用实际页面的情况下预先构建页面缓存?

我查看了类似 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/

相关文章:

php - 如何使用 Zend Framework 2 设置 Redis 缓存?

java - "Failed to deserialize object"在点燃缓存中插入对象时出错

asp.net - HttpRuntime.Cache 在 Windows Azure 上的高负载下损坏数据

ruby-on-rails - 在 Rails 中动态包含对象的关联

ruby-on-rails - Rails - 如何选择表格中的最后一个日期?

ruby-on-rails - 基于小时的 ActiveRecord 范围

ruby-on-rails - Rails - 如何检查一个变量是否存在以及它是否在一条语句中具有特定值

ruby-on-rails - Rails 范围为 null 或为空?

ajax - Grails:每次 ajax 调用时发送缓存头的最佳方式

javascript - react 不重新获取过期的缓存文件