I am new to Redis and Rails caching, and would like to perform simple model caching. I have just read these 2 articles :
http://www.sitepoint.com/rails-model-caching-redis/
http://www.victorareba.com/tutorials/speed-your-rails-app-with-model-caching-using-redis
Since Redis model caching consists in storing JSON strings in redis and retrieving them with code like
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
I don't understand what is the need of using
gem 'redis-rails'
gem 'redis-rack-cache'
I don't see where the cache store or other caching mechanisms are at use in that kind of examples, since they consist only in reading/writing to Redis.
Thank you for any help.
Here is what I have in my Gemfile
gem 'redis'
gem 'readthis'
gem 'hiredis'
gem 'redis-browser'
readthis - recently implemented nice feature to not crash Rails when Redis is down Disable Rails caching if Redis is down. And it supports advanced Redis data types (not just strings as redis-rails).
hiredis - is a little faster
redis-browser - allows me to see what is actually cached (easier than cli).
Here is my 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 }
Then in my models I do:
def my_method_name
Rails.cache.fetch("#{cache_key}/#{__method__}", expires_in: 1.hour) do
# put my code here
end
end
I used https://github.com/MiniProfiler/rack-mini-profiler to see which queries were firing lots of DB request and determined what I should cache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With