In this fifth part of a six-part article series on optimizing the performance of a Ruby on Rails program, you'll learn how to use memcached to cache and store data. This article is excerpted from chapter 13 of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
On other *nix variants, you can use their native package management systems to install memcached or do it by hand. We do the latter, because that way we get the latest version of memcached. Download and compile memcached as follows (check the latest version fromdanga.com/memcached/download.bml):
If theconfigurecommand nags about missinglibevent, install thelibevent-devpackage (again, withapt-getor equivalent, or by hand fromhttp://www.monkey.org/~provos/libevent/) and rerunconfigure. Be sure to read the notes in theREADMEfile in the memcached source distribution if you’re on Linux.
On Windows, the support for memcached is a bit flaky. There is no official distribution, but you might want to test if the release athttp://jehiah.com/projects/memcached-win32/works for you.
After you’ve installed memcached, you need to install theruby-memcachegem, which is used to interface with memcached:
Now that memcached is installed, you might as well start it. Run it with the-vvcommand to get verbose output of everything that’s happening in it.
$ memcached -vv
-------------------------------------------- ... <4 server listening (udp) --------------------------------------------
This will start the memcached server with its default values: port 11211 and 64MB of memory. The server will stay in the foreground, so you can monitor that it’s working correctly.
Now you need to make your application use memcached. Add the following line at the end ofconfig/environments/production.rb:
Restart the application server, and the new memcached store should be in use. Try to load a page that includes a shopping cart. You should see memcached output something like the following:
--------------------------------------------<8 new client connection <8 get emporium.com:3000/cart/show/107 >8 END <8 set emporium.com:3000/cart/show/107 4 0 311 >8 STORED --------------------------------------------
That’s it—our fragment cache is on memcached.
At this point, you would probably want to restart the memcached process, perhaps give it some more memory (128MB should be enough for most Rails applications, but your mileage may vary) with the-moption, and make it run in the background using the-doption:
$ memcached -d -m 128
It is also a good idea to monitor the memcached process, just as you watch any other server process. You can use one of the monitoring tools mentioned in the previous chapter for this.