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
- 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.
- Just install dalli gem
- Install memcached server
- Start the memcached server if not started
- Configure in your environments, add the following in your production.rb file
config.action_controller.perform_caching = true
Add the following in your gem file and do bundle install
$ gem 'dalli', '2.0.2' $ bundle install
$ sudo apt-get install memcached
$ sudo /etc/init.d/memcached start
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