Skip to content

Instantly share code, notes, and snippets.

@jimneath
Created September 26, 2012 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimneath/e52ec75714772648f285 to your computer and use it in GitHub Desktop.
Save jimneath/e52ec75714772648f285 to your computer and use it in GitHub Desktop.

Using Memcached on EY Cloud

What is memcached

Memcached is a high-performance, in-memory key-value store that can be used to speed up your Rails applications by caching the results of database calls, API calls or page rendering.

Using memcached in a clustered environment

Rails 3

The memcached client that we recommend for use with Rails 3 is Dalli by Mike Perham, the former maintainer of the memcache-client gem.

The first step is to add dalli to your Gemfile:

gem 'dalli'

By default, EY Cloud sets up and monitors memcached on solo, app master and app instances. We also write a memcached config file, memcached.yml, to your application's shared config directory, /data/yourapp/shared/config/. This file will be symlinked to /data/yourapp/current/config/memcached.yml when you deploy your application.

Finally, we need to parse the memcached.yml and tell Dalli where our memcached servers are located. We can do this by adding the following to config/environments/production.rb:

# parse the memcached.yml
memcached_config = YAML.load_file(Rails.root.join('config/memcached.yml'))[Rails.env]
memcached_hosts = memcached_config['defaults']['servers']     

# pass the servers to dalli setup
config.cache_store = :dalli_store, *memcached_hosts

When app instances are added or removed, your memcached.yml will be updated automatically. So your application will always be using the correct hosts.

Rails 2.3

Unfortunately, Dalli offers no support for Rails 2.3 applications. However, Rails 2.3 comes with a prebundled version of the memcache-client. We simply need to make the following updates to config/environments/production.rb:

# parse the memcached.yml
memcached_config = YAML.load_file(Rails.root.join('config/memcached.yml'))[Rails.env]
memcached_hosts = memcached_config['defaults']['servers']
     
# pass the servers to memcached setup
config.action_controller.cache_store = :mem_cache_store, *memcached_hosts

Using a utility instance as your memcached server

To run memcached on a utility instance, first of all, follow the steps listed above to setup your cache store to use the hosts listed in memcached.yml.

Next, you will have to use a custom chef recipe to setup memcached to run on your utility instance. The following is an example of a chef recipe that will setup memcached on a utility instance named memcached. It will then write a new version of memcached.yml that points to the utility instance.

https://github.com/jimneath/ey-memcached-util

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment