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

Unknown's avatar

Author: Abhilash

Hi, Iโ€™m Abhilash! A seasoned web developer with 15 years of experience specializing in Ruby and Ruby on Rails. Since 2010, Iโ€™ve built scalable, robust web applications and worked with frameworks like Angular, Sinatra, Laravel, Node.js, Vue and React. Passionate about clean, maintainable code and continuous learning, I share insights, tutorials, and experiences here. Letโ€™s explore the ever-evolving world of web development together!

Leave a comment