Friday, 1 August 2014

Working with memcached in Ruby on Rails

Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.
Memcached is free and open-source software. Memcached runs on Unix-like (at least Linux and OS X) and on Microsoft Windows.

here is example to use in Ubuntu:

1.installation:  sudo apt-get install memcached
2.setup in rails:  gem install dalli
 (dalli is gem to use memcached in rails)
3.configure Rails: there are two ways to use memcached in rails:

a).Using Rails cache as memcached: 
 write following lines of code in :
config/environments/production.rb (development.rb,staging.rb) as per environment.
config.cache_store = :dalli_store
config.action_controller.perform_caching = true
 
b).Using system memcached: follow these steps
 
class MemCacheClass
 
def initialize
     @connection ||= Dalli::Client.new("#{host}:#{port}", compress: true) 
   // where host is host and port is the port on which memcached is running
 default is 11211.
end

  def get(key)
    @connection.get(key) // return the value for given key.
  end

  def set(key,value, time_stamp)        
    @connection.set(key, value, time_stamp)
  end
 end
 
Uses: you can get and values from memcached
 
Get Value : 
conn = MemCacheClass.new
conn.set(key,value,time) // set value of key to given value for given
time period
conn.get(key) // get value of given key.