Rails 4简单模型缓存与Redis

ste*_*cdn 4 ruby caching model redis ruby-on-rails-4

我是Redis和Rails缓存的新手,并希望执行简单的模型缓存.我刚读过这两篇文章:

http://www.sitepoint.com/rails-model-caching-redis/

http://www.victorareba.com/tutorials/speed-your-rails-app-with-model-caching-using-redis

因为Redis模型缓存包括在redis中存储JSON字符串并使用类似的代码检索它们

def fetch_snippets
  snippets =  $redis.get("snippets")
  if snippets.nil?
    snippets = Snippet.all.to_json
    $redis.set("snippets", snippets)
  end
  @snippets = JSON.load snippets
end
Run Code Online (Sandbox Code Playgroud)

我不明白使用的必要性

gem 'redis-rails'
gem 'redis-rack-cache'
Run Code Online (Sandbox Code Playgroud)

我没有看到缓存存储或其他缓存机制在这种示例中的使用位置,因为它们只包含对Redis的读/写.

感谢您的任何帮助.

Dmi*_*sky 11

这是我在Gemfile中的内容

gem 'redis'
gem 'readthis'
gem 'hiredis'
gem 'redis-browser'
Run Code Online (Sandbox Code Playgroud)

readthis - 最近实现了很好的功能,当Redis 关闭时不会崩溃Rails如果Redis关闭,则禁用Rails缓存.它支持高级Redis数据类型(不仅仅是字符串作为redis-rails).

hiredis - 快一点

redis-browser - 允许我查看实际缓存的内容(比cli更容易).

这是我的application.rb

config.cache_store = :readthis_store, { expires_in: 1.hour.to_i, namespace: 'foobar', redis: { host: config.redis_host, port: 6379, db: 0 }, driver: :hiredis }
Run Code Online (Sandbox Code Playgroud)

然后在我的模型中我做:

def my_method_name
  Rails.cache.fetch("#{cache_key}/#{__method__}", expires_in: 1.hour) do
    # put my code here
  end
end
Run Code Online (Sandbox Code Playgroud)

我使用https://github.com/MiniProfiler/rack-mini-profiler查看哪些查询触发了大量数据库请求并确定了应该缓存的内容.