Memcached with Rails 3

I never had a reason to play with memcached and it was on my list of things to learn. Below I will demonstrate an example app very quickly and simply. I’m not doing anything more complicated than simple primitive storing. If you are going to store any objects in memcached, dalli gem will take care of this for you (ymmv).

First let’s create a rails app and an rvm gemset to play in.

If you don’t have rails in your global gemset, you can install rails now. I used the 3.1 RC here just to test out 3.1 and memcached at the same time.

Dalli is written by Mike Perham (awesome guy) and simply wires up Rails.cache to be our memcached server. This is convenient and more standard than creating your own global variable or other configuration.

Next, let’s install memcached if we haven’t already:

You can also start memcached as a service under Mac using the homebrew instructions. I like to leave things in the foreground when I’m first setting them up or grok’ing.

Ok, now we can create our dummy app.

Our dummy rails app is going to have a slow controller action in it. In this case, it could be a row count of a huge database. In your case it could be a slow network call or a result of an expensive SQL operation.

First, edit your Gemfile:

Edit config/environments/development.rb

Rails c should work at this point and this line:

Now generate a controller:

Create a route in routes.rb:

Create a simple view in app/views/posts/index.json.erb:

Now when you hit the page it should be slow the first time but fast the second time. After 3 seconds, it’s slow again.

So you can see that memcached returned the cached object and avoided the sleep call. In the real world, this would equate to lower page rendering time or better application performance.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">