Skip to main content

Caching in Rails with memcached?

Caching in Rails with memcached ?

Installation

1. Follow this link to download and install memcached.
2. Start the memcached server using either

memcached -vv

or

/etc/init.d/memcached start

Integrating memcached with your rails application.

1. Install memcache-client

gem install memcache-client

2. Add the below line to  end of your config/environment.rb file.

CACHE = MemCache.new('127.0.0.1')

3. Add the following method to your application controller / application helper or where ever you want according to your need.

def perform_cache(key)
  begin
   unless output = CACHE.get(key)
     output = yield
     CACHE.set(key, output, 15.minutes)
   end
 rescue => e
  logger.info “MEMCACHE ERROR++++++++++++++++++++++++++++++++++++”
  logger.info “ERROR : #{e.message}”
  logger.info “MEMCACHE ERROR++++++++++++++++++++++++++++++++++++”
  output = yield
  end
  return output
 end

The above method performs the caching based on a unique key. If the value for that key already exists, it will return the output from the stored cache or  else it will execute the block you are using when calling the above method and generate a new value from the executed block for the particular key and store it in the cache.

You can set a timer to expire the cached data.(15 mins in my case.)

If you don’t want to expire the cache based on timer, simply remove the third parameter we are passing to ’set’ method.

The above method also handles the exception,in case your memcache server is down for some reason.

4.  Cache your complex queries/methods as follows.

my_key =  Digest::MD5.hexdigest(request.request_uri)
output = perform_cache(my_key) { ClassName.method_name(…) }

Note : The key generated should be always unique, otherwise it will overwrite your existing cached data already having the same key. I am using the URL as the key, Since the URL is pretty long we can take the MD5 hash/SHA1 hash of it and use it as the key.

5.  You can edit memory  used by memcached as follows.

Open /etc/sysconfig/memcached file and edit “CACHESIZE” entry,
this entry is in MBs.

That's it your ready to go.

Comments

Popular posts from this blog

Create dynamic sitemap on ruby on rails

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site. It’s basically a XML file describing all URLs in your page: The following example shows a Sitemap that contains just one URL and uses all optional tags. The optional tags are in italics. <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">    <url>       <loc>http://www.example.com/</loc>       <lastmod>2005-01-01</lastmod>       <changefreq>monthly</changefreq>     ...

Omniauth Linked in Ruby On Rails

def get_linkedin_user_data      omniauth = request.env["omniauth.auth"]      dat=omniauth.extra.raw_info      linked_app_key = "xxxxxxx"      linkedin_secret_key = "yyyyyyy"      client = LinkedIn::Client.new(linked_app_key,linkedin_secret_key)      client.authorize_from_access(omniauth['credentials']['token'],omniauth['credentials']['secret'])      connections=client.connections(:fields => ["id", "first-name", "last-name","picture-url"])      uid=omniauth['uid']      token=omniauth["credentials"]["token"]      secret=omniauth["credentials"]["secret"]   #linked user data     omniauth = request.env["omniauth.auth"]      data             = omniauth.info      user_name...

Install Rvm on ubuntu

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev curl -L https://get.rvm.io | bash -s stable source ~/.rvm/scripts/rvm rvm install 2.0.0-p645 rvm use 2.0.0-p645 --default ruby -v rvm gemset create rails3.2.8 rvm gemset use rails3.2.8 gem install rails -v 3.2.8