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.
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.
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
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.