1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Using Memcache in Ruby Programs

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    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:

    Code:
    $ gem install memcached
    

    Accessing Memcached



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

    Code:
    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.
     
    shabbir likes this.

Share This Page