Rails MemCacheStore and dalli gem

We can use a memcached server for centralized caching in our application. This server is handling all caching mechanisms. Rails is using the gem memcache-client by default. But here I am using the dalli gem. Because it is better than memcache-client, but one thing to say is I am not experienced this. By reading documents, I have concluded that. You just go through this dalli gem link, https://github.com/mperham/dalli. This is a super caching mechanism by Rails in production environments. The Only thing we need to do is

  1. Say you want caching in your application, by adding the following in your environments, add the following in your production.rb file, if you are running in production mode and you are using production.rb file as your environment configuration file.
  2. config.action_controller.perform_caching = true
  3. Just install dalli gem
  4. Add the following in your gem file and do bundle install

    $ gem 'dalli', '2.0.2'
    $ bundle install
    
  5. Install memcached server
  6. $ sudo apt-get install memcached
  7. Start the memcached server if not started
  8. $ sudo /etc/init.d/memcached start
  9. Configure in your environments, add the following in your production.rb file
  10. config.cache_store = :dalli_store, 'YOUR_PRODUCTION_PUBLIC_DNS:11211',
        { :namespace => "app-YOUR_HOST", :expires_in => 1.day, :compress => true }
    

    Here ‘YOUR_PRODUCTION_PUBLIC_DNS:11211’ is saying where your memcached server is running. Public DNS and the port number of the memcached server.

Take the rails console and experiment something like the following to know the MemCacheStore cache mechanism is working. If you are in localhost then do

ruby-1.9.2-p290 :003 > cache = Dalli::Client.new('localhost:11211')
 => #0}, @ring=nil> 
ruby-1.9.2-p290 :004 > cache.set('testing', 1234)
 => true
ruby-1.9.2-p290 :006 > cache.get('testing')
 => 1234

Now you are ready to go

Advertisements

Author: Abhi

Hi, this is Abhilash - Senior Programmer Analyst at CoMakeIT, specialised on web programming. Mainly working on Ruby On Rails platform since 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s