Rails using memcache for everything

The Rails documentation for using memcache is a little skimpy. I eventually worked out how to use it for a Session store by googling. The Fragment cache store was a little easier.

Here’s the relevant parts of my environment.rb file:

require 'memcache'

memcache_options = {
   :compression => false,
   :debug => false,
   :namespace => "app-#{RAILS_ENV}",
   :readonly => false,
   :urlencode => false
}
memcache_servers = [ '192.168.1.150:2222', '192.168.1.150:2223' ]

Rails::Initializer.run do |config|
  ....
  config.action_controller.session_store = :mem_cache_store
  ...
  config.action_controller.fragment_cache_store = :mem_cache_store, memcache_servers, memcache_options
  ...
end

...
cache_params = *([memcache_servers, memcache_options].flatten)
CACHE = MemCache.new *cache_params
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.merge!({ 'cache' => CACHE })

The order of these things is important – the DEFAULT_SESSION_OPTIONS can’t be changed until after the Initializer has finished, for instance.

This configuration gives me:
  1. Session store in Memcache
  2. Fragment cache in Memcache
  3. A global CACHE object I can use to cache Model objects

It’s annoying that the configuration for the Session store and Fragment cache aren’t the same – oh well.

Update: Fixed a bug in the passing of parameters to the setup of the CACHE object.

This entry was posted on Sat, 14 Jan 2006 02:09:00 GMT . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.
Tags


Trackbacks

Use the following link to trackback from your own site:
http://blog.craz8.com/trackbacks?article_id=rails-using-memcache-for-everything&day=13&month=01&year=2006

Comments

Leave a response

  1. Gregor Melhorn 9 months later:

    adding this right after bootstrap in environment.rb fixed it, hope it gets integrated in the core soon.

    class ActionController::Caching::Fragments::MemCacheStore def initialize(addresses) super() addresses = addresses.flatten addresses = [“localhost”] if addresses.empty? @addresses = addresses @data = MemCache.new @data.servers = [addresses] end end

  2. Gregor Melhorn 9 months later:
    
    class ActionController::Caching::Fragments::MemCacheStore
      def initialize(*addresses)
        super()
        addresses = addresses.flatten
        addresses = ["localhost"] if addresses.empty?
        @addresses = addresses
        @data = MemCache.new
        @data.servers = [*addresses]
      end
    end
    
  3. Tom 9 months later:

    That sucks. Did you submit a patch for this bug?

Leave a comment