Using Memcache in Ruby Programs

pradeep's Avatar author of Using Memcache in Ruby Programs
This is an article on Using Memcache in Ruby Programs in Ruby on Rails.
Rated 4.00 By 1 users
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:

$ 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 ="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.
shabbir like this