简体   繁体   English

Memcached用于Rails中的片段机器

[英]Memcached for fragment cachine in Rails

I'm trying to figure out the best way to set organize the caching system for my scenario: 我试图找出为我的场景设置组织缓存系统的最佳方法:

My web app has "trending movies," which are basically like twitter's trending topics -- the popular topics of conversation. 我的Web应用程序具有“流行电影”,基本上类似于Twitter的热门话题-对话的热门话题。 I've written the function Movie.trending , which returns an array of 5 Movie objects. 我编写了函数Movie.trending ,该函数返回5个Movie对象的数组。 However, since calculating the trending movies is fairly CPU intensive and it will be shown on every page, I want to cache the result and let it expire after 5 minutes. 但是,由于计算趋势电影的工作量相当大,并且会在每个页面上显示,因此我想缓存结果并让其在5分钟后过期。 Ideally, I'd like to be able to call Movie.trending from anywhere in the code and assume that cachine will work how i expect it to -- if the results are 5 minutes or earlier, then renew the results, otherwise, serve the cached results. 理想情况下,我希望能够从代码中的任何位置调用Movie.trending ,并假设cachine将按我期望的方式工作-如果结果是5分钟或更早,则更新结果,否则,将结果送达缓存的结果。

Is fragment caching the right selection for a task like this? 对于这样的任务,片段缓存是否是正确的选择? Are there any additional gems I ought to be using? 我还应该使用其他宝石吗? I'm not using Heroku. 我没有使用Heroku。

Thanks! 谢谢!

To reach this model's caching you can try Rails.cache.fetch, see the example below: 要达到此模型的缓存,可以尝试Rails.cache.fetch,请参见下面的示例:

# model - app/models/movie.rb
class Movie
  def self.trending
    Rails.cache.fetch("trending_movies", :expires_in => 5.minutes) do
      # CPU intensive operations
    end
  end
end

# helper - app/views/helpers/application.rb
module ApplicationHelper
  def trending_movies
    content_tag :div do
      Movie.trending
    end
  end
end

# view - app/views/shared/_trending_movies
trending_movies

To test it in development mode don't forget to turn on caching for a specific environment 要在开发模式下对其进行测试,请不要忘记为特定环境打开缓存

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

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