Skip to content

Cache results of timeconsuming stuff in redis leveraging redis expiration.

Notifications You must be signed in to change notification settings

kbaum/simple_redis_cache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SimpleRedisCache

Easily cache the result of a block within redis for a given time period.

Let's cache something for 1 minute

    class MyClass

      include SimpleRedisCache

      def hello
        cache('hello', :ttl=>60){ 'world' }
      end
    end

Call it straight from the module instead and this time cache it forever.

    SimpleRedisCache.cache('hello') { 'world' }

Maybe we should cache something worth while. If the result of the block is not a string, make sure to convert it to one.

  require 'json'

  JSON.parse(cache('20_perm_4', :ttl=>120){ (0..20).to_a.permutation(4).to_a.to_json })

Notice we serialize to json inside the block and from json outside the block. Of course converting an enormous array to and from JSON is slower than the permutation so maybe it's not the best example. Replace the above with an expensive databse calculation and it makes more sense.

The above uses the default Redis.new instance running on 127.0.0.1:6379

Let's configure a different redis instance.

  SimpleRedisCache::Config.redis =  Redis.new(:host => "10.0.1.1", :port => 6380)

My benchmarks show this is faster than your current cache.

But why would I use this?

Because you already depend on redis through Resque.

About

Cache results of timeconsuming stuff in redis leveraging redis expiration.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages