【问题标题】:Cache expensive JBuilder result from frequent resquest缓存来自频繁请求的昂贵的 JBuilder 结果
【发布时间】:2017-06-10 16:28:57
【问题描述】:

我有一个使用 JBuilder 生成 Json 响应的端点。 但是,这个 Json 制作起来很慢,而且由于这个请求每隔几秒发出一次,而且不需要每次都更新,所以我决定缓存它。

这是一个带有嵌套属性的复杂 Json,它访问一些模型关联。

如何缓存 json 结果并每隔 x 分钟将其呈现给用户?

file.json.jbuilder:

json.array!(@photos) do |photo|
  json.extract! photo, :id, :title, :description, :image_updated_at
  json.camera_roll_image_url URI.join(request.url, photo.image.url(:camera_roll)).to_s
  json.original_image_url URI.join(request.url, photo.image.url).to_s
  json.has_picture true

  json.girl do 
    json.extract! photo.girl, :id, :name, :phone, :ddd, :country_code, :approved, :gender, :likes, :is_ad, :ad_type
    json.user_liked photo.girl.liked_by_user?(@user)
    if(photo.girl.is_ad == 1)
      json.ad_info do
        json.extract! photo.girl, :price, :description, :address, :ad_type
      end
    end
    json.is_featured photo.girl.is_featured? 
    json.avatar URI.join(request.url, photo.girl.avatar.url(:thumb)).to_s
    json.age photo.girl.age
    json.country_num_code photo.girl.country_num_code
    json.type photo.girl.type
  end

  json.check_in do
    json.extract! photo.girl.check_ins.last, :latitude, :longitude
  end

  json.userLat @userLat
  json.userLong @userLong

  json.likes photo.likes
  json.user_liked photo.liked_by_user? @current_user
end

【问题讨论】:

    标签: ruby-on-rails caching jbuilder


    【解决方案1】:

    好吧,rails 中集成了多种缓存机制。您可以在指南中了解它们:http://guides.rubyonrails.org/caching_with_rails.html

    在您的具体情况下,有几种选择,它们都有很高的成功机会。

    在缓存任何东西之前,我想找出最昂贵的部分,然后缓存那个部分,看看它是否足够好。

    如果您的客户很聪明,您也可以使用 etag,但所有这些都在很大程度上取决于您的用例(在缓存方面总是如此)。

    旁注,如果你有 nginx 之类的东西,可以将其用作反向代理 https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      相关资源
      最近更新 更多