A simple, JSON-oriented wrapper around Redis that provides easy mechanisms for keeping your cache fresh.
Set up a Redis client instance as $redis in your config files either as an initializer or in your environments files.
$redis = Redis.new(:host => 'localhost', :port => 6379)
This is where you'd set up a namespace, if you want one.
FreshRedis.get("foo")
FreshRedis.freshen("foo", 5.minutes, :ruby) do
{your_age: 30}
end
This will return the value as a Ruby object (Hash, Array, etc)
- 'freshen' will freshen the value if the expiration time has expired and will return the cached value if it hasn't.
- 'freshen' will always return the value whether it's retrieved from the cache or it's evaluated in the block. That means it's a great choice for wrapping existing expensive code in a block for out-of-the-box caching.
If you know you'll be returning JSON, you can skip the parsing of the stored JSON into a Ruby object by specifying the format as :json for extra performance.
FreshRedis.freshen("foo", 5.minutes, :json) do
{your_age: 30}
end
You can set the expire time to 0.minutes to effectively disable caching.
FreshRedis.set("foo", {your_age: 30})
FreshRedis.unset("foo")
That's it!
My most common use-case is this:
response.content_type = "application/json"
return render text: FreshRedis.freshen("dude_this_is_expensive", 5.minute, :json) do
calculate_and_return_some_expensive_thing
end