Using Memcache in Ruby Programs

Discussion in 'Ruby on Rails' started by pradeep, Feb 19, 2013.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    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.

    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 likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice