Book Image

Getting Started with Memcached

By : Ahmed Soliman
Book Image

Getting Started with Memcached

By: Ahmed Soliman

Overview of this book

<p>Web application performance is no longer a non-functional requirement, but an implicit condition for an engaging user experience. As a result, responsive and highly scalable applications are becoming a necessity. Memcached is a high-performance distributed memory caching system built to speed up dynamic web applications by offloading pressure from your database. <br /><br />Getting Started with Memcached is a hands-on, comprehensive guide to the Memcached service and it’s API in different programming languages. It contains practical recipes to integrate Memcached within your Rails, Django, or even Scala Play! applications.<br /><br />This book will show you everything you need to know to start using Memcached in your existing or new web applications.<br />This book uses real-world recipes to help you learn how to store and retrieve data from your clustered virtual memory cache pool and how to integrate caching into your favourite web development framework.</p> <p><br />You will also learn how to build a Memcached consistent-hashing scalable cluster and how Memcached clients are properly configured to use different servers to scale out your memory cache pool in Ruby, Python, PHP, and Java. With this book, you will see how to cache templates and database queries in the most popular web development framework in use today.</p>
Table of Contents (9 chapters)

Setting up memcached support in Rails (Simple)


Ruby on Rails Web development framework is extremely popular for rapid development of Web applications and, at some point in time it started an actual movement for a set of convention-over-configuration frameworks and most likely you have used one of them recently if you are a seasoned web developer.

We are assuming that you are familiar with Rails and you already have some experience using rails caching API, but even if you are not, that's a good introduction about caching in Rails anyway.

We will be using Dalli as the memcached client and we will be configuring a simple Rails application to use it as a backend for Rails Caching. If you want more information about Rails caching in general, you are advised to visit http://guides.rubyonrails.org/caching_with_rails.html.

Getting ready

You will need to have a working Rails installation on your system for that, you can find great tutorials on the Web for that, such as this one https://www.digitalocean.com/community/articles/how-to-install-ruby-on-rails-on-ubuntu-12-04-lts-precise-pangolin-with-rvm.

How to do it...

  1. Let's now start by creating a really simple Rails application as a mock, to be the test base for our caching experiments: rails new cachesample.

  2. In a few minutes, you will have your empty Rails application ready, you can run it using:

    cd cachesample/
    rails server
  3. You should see something like the following:

    => Booting WEBrick
    => Rails 4.0.0 application starting in development on http://0.0.0.0:3000
    => Run `rails server -h` for more startup options
    => Ctrl-C to shutdown server
    [2013-10-29 16:40:56] INFO  WEBrick 1.3.1
    [2013-10-29 16:40:56] INFO  ruby 2.0.0 (2013-06-27) [x86_64-linux]
    [2013-10-29 16:40:56] INFO  WEBrick::HTTPServer#start: pid=18450 port=3000
  4. Now, we need to configure our Rails application to use Dalli gem as a dependency.

  5. Edit your Gemfile and add this line at the end of the file:

    gem 'dalli'
  6. Then, you will need to run:

    bundle install

Now, we need to edit the application configuration to actually use memcached as the caching backend for the rails caching API.

Normally, you don't enable caching while development and you only turn it on in production, so we will be editing the config/environments/production.rb file (you may also want to add this to config/environments/development.rb if you want to see caching in development mode). Let's add:

 config.cache_store = :dalli_store

How it works...

You will be able to use all of Rails automatic and manual caching features of Rails and the default cache store will be now Dalli (memcached client).

Rails has different features for caching, such as the following:

  • Action caching: It caches an action response based on the input parameters and every request will go to all the before filters, this means that authentication is verified for example.

  • Fragment caching: This means that specific pieces of template code can be cached, this is very useful, specially if you are building a huge page that contains pieces that are constantly changing and dynamic, you still can modularize parts of the page and cache those parts as fragments. For example, you want to cache a fragment that generates a list of products:

    <% Order.find_recent.each do |o| %>
      <%= o.buyer.name %> bought <%= o.product.name %>
    <% end %>
    
    <% cache do %>
      All available products:
      <% Product.all.each do |p| %>   <%= link_to p.name, product_url(p) %>
      <% end %>
    <% end %>
  • SQL caching: This is a feature that allows Rails to cache results of a SQL query so that if it encountered the same query again for that request, it will use the cached result set and will not be running the same query again on the database server.

There's more...

To use Dalli for Rails session storage that times out after 20 minutes, in config/initializers/session_store.rb:

config.cache_store = :dalli_store, 'cache-1.example.com', 'cache-2.example.com',
  { :namespace => NAME_OF_RAILS_APP, :expires_in => 1.day, :compress => true }

Of course, you will need to write the correct names of the memcached hosts and ports for your caching cluster, instead of cache-1.example.com and cache-2.example.com.