Ruby on rails Memcached用于Rails中的片段cachine
我正在尝试找出为我的场景设置和组织缓存系统的最佳方法: 我的网络应用程序有“趋势电影”,基本上就像推特的趋势主题——流行的对话主题。我已经编写了函数Ruby on rails Memcached用于Rails中的片段cachine,ruby-on-rails,ruby,ruby-on-rails-3,memcached,Ruby On Rails,Ruby,Ruby On Rails 3,Memcached,我正在尝试找出为我的场景设置和组织缓存系统的最佳方法: 我的网络应用程序有“趋势电影”,基本上就像推特的趋势主题——流行的对话主题。我已经编写了函数Movie.trending,它返回5个Movie对象的数组。然而,由于计算趋势电影是相当CPU密集型的,它将显示在每个页面上,我想缓存结果,让它在5分钟后过期。理想情况下,我希望能够从代码中的任何位置调用Movie.trending,并假设cachine将按我期望的方式工作--如果结果为5分钟或更早,则更新结果,否则,提供缓存结果 对于这样的任务,
Movie.trending
,它返回5个Movie
对象的数组。然而,由于计算趋势电影是相当CPU密集型的,它将显示在每个页面上,我想缓存结果,让它在5分钟后过期。理想情况下,我希望能够从代码中的任何位置调用Movie.trending
,并假设cachine将按我期望的方式工作--如果结果为5分钟或更早,则更新结果,否则,提供缓存结果
对于这样的任务,片段缓存是正确的选择吗?有没有其他我应该使用的宝石?我没有用Heroku
谢谢 要访问此模型的缓存,您可以尝试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
要在开发模式下对其进行测试,请不要忘记打开特定环境的缓存要达到此模型的缓存,您可以尝试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
要在开发模式下进行测试,请不要忘记为特定环境启用缓存