Mohit Jain
Mohit Jain

Reputation: 43919

How to use two different memcache instances on heroku

I am storing database query results in memcache on heroku. I am using memcachier addon on heroku. For example if I have a cache User's tasks in memcache. I do something like this:

 def cached_tasks
   Rails.cache.fetch([:users, id, :tasks], :expires_in => 12.hours) { tasks.to_a }  
 end

This works perfectly fine but I want to use two different memcache instances to store data.

Why?

One that is used very frequently, basically data changes frequently and another for those which are big data objects and those will never change or very rarely.

How can I use two different instances and specify that cached_tasks should be stored in memcache_instance_1 and other like cached_images should be stored in memcache_instance_2

Why not to use the same one:

Because sometimes I need to flush the whole cache and that will flush the big data too which I don't want to.

Any suggestions?

Upvotes: 2

Views: 352

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

Declare three new env variables for your heroku app

BIG_MEMCACHIER_SERVERS
BIG_MEMCACHIER_USERNAME
BIG_MEMCACHIER_PASSWORD

Add a file called big_cache.rb in the config\initializers directory:

module Rails
  def self.big_cache
    @big_cache ||= ActiveSupport::Cache::DalliStore.new(
      (ENV["BIG_MEMCACHIER_SERVERS"] || "").split(","),
      :username => ENV["BIG_MEMCACHIER_USERNAME"],
      :password => ENV["BIG_MEMCACHIER_PASSWORD"])
  end
end

Now you can access the 2nd cache as follows:

Rails.big_cache.fetch(..)

Upvotes: 3

Elad Meidar
Elad Meidar

Reputation: 814

What i would do is to try and define what from the the things i am caching is actually something that requires cache, or it actually needs some life-limited persistency.

I would leave the Rails internal caching system to do what it does best: page, action and fragment caching, and use another persistency engine (such as Redis) to hold and maintain those large objects you talked about (implementation of this suggestion is a completely different question).

note that Redis also allows setting a TTL (time to live) on keys - so it can provide this life limited persistency that you want.

Upvotes: 0

Related Questions