Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Ruby on Rails (http://www.go4expert.com/articles/ruby/)
-   -   Using Memcache in Ruby Programs (http://www.go4expert.com/articles/using-memcache-ruby-programs-t29500/)

pradeep 19Feb2013 18:43

Using Memcache in Ruby Programs
 
Memcache is a high-performance open-source caching server daemon and it's robust, fast & distributed system. Memcached has a client-server model, the memcached daemon listens of default port 11211, which obviously can be configured to our requirements.

In this article we will be looking at a Ruby gem which will be used to implement the benefits of memcache in our Ruby programs, the memcache gem uses libmemcached C library which makes it faster than pure-Ruby memcache gems. I had earlier written an article Faster Webapps With Memcache, which is a good read for beginners.

Installing The Gem



To install the gem just issue the following command in shell:

Code:

$ gem install memcached


Accessing Memcached



Memcached Ruby gem is pretty easy to use, the following code snippets will be self-explanatory.

Code: Ruby

require 'rubygems'
require 'memcached'

## connect to Memcached instance running on localhost on the default port 11211
mcache_obj = Memcached.new("localhost:11211")

## set a key/value pair
mcache_obj.set 'myName', 'Anjali'

## get the value
mcache_obj.get 'myName' # returns "Anjali"

## getting multiple keys' values at once
mcache_obj.get ['myName', 'BadKey', 'myName1']

## returns {"myName" => "Anjali", "BadKey" => "Anjali" }

## delete key
mcache_obj.delete 'myName'

## set a key/value with expiry, set to expire after 60 secs
mcache_obj.set 'myName', 'Anjali', 60

## you can also increment values, like counters etc.
mcache_obj.set 'Mycounter', 1.to_s, 0
mcache_obj.increment 'Mycounter' # value becomes 2
mcache_obj.increment 'Mycounter' # value becomes 3


I hope this was helpful in getting you started with using memcached in your Ruby programs.


All times are GMT +5.5. The time now is 09:29.