Saturday, December 15, 2012

Memcached with Ruby on rails


How to use Memcached in a Rails application

Caching is one of the techniques used for improving the overall performance of a web site. One of the most common servers for caching is memcached.

Installation

To install memcached server in Ubuntu use following command in terminal:

 sudo apt-get install memcached
 sudo apt-get install libmemcached-dev libmemcached-tools

Start, stop and restart memcached service

 sudo /etc/init.d/memcached start 
 sudo /etc/init.d/memcached stop
 sudo /etc/init.d/memcached restart

Configuring a Rails App to use memcached

Add the following Gem to yout Gemfile
 
gem 'dalli'
gem 'kgio'
Dalli is the gem used for comunicating with memcached and kgio improves the read/write performance. After editing the Gemfile we run bundle install command in the terminal.
Now that you have the gems installed, you need to tell rails to use it.

Configuring a Rails App environment file

In production.rb and development.rb, staging.rb, set the cache_store :

 # /config/environments/production.rb
 config.cache_store = :dalli_store
# /config/environments/development.rb
config.cache_store = :dalli_store

# /config/environments/staging.rb
config.cache_store = :dalli_store

Now change your session initializer (for memcache session support)

 # config/initializers/session_store.rb

require 'action_dispatch/middleware/session/dalli_store' YOURAPPNAMEHERE::Application.config.session_store :dalli_store

Testing if all is well

Open a rails console and test setting a value and after getting the same value.

$ rails c
 
> require 'dalli'
> ca = Dalli::Client.new('localhost:11211')
> ca.set('naim', 123)
> value = dc.get('naim') 

References:

  1. Memcached
  2. Dalli
  3. kgio