memcached Basics for Rails
Posted by topfunky
4 hours
ago
Many speedy sites use
memcached to save the results of expensive database queries and
intense rendered templates. This is a basic introduction to using
memcached with Rails. Thanks to Eric Hodel and Layton Wedgeworth
who have answered many questions.
Yes, there is a hash in the sky
Memcached is a lightweight server process that stakes out a
fixed amount of memory and makes it available as a quick access
object cache.
Some of the things you can do with it are:
- Automatically cache a row from the database as an ActiveRecord
object
- Explicitly
render_to_string and save the results
(works well for tag clouds)
- Manually store a complicated database query and retrieve it
later
I thought there was some kind of fancy voodoo happening, but it
turns out that it’s basically just a hash! You can put
a key and value into the cache, and get it later.
memcache-client
also gives you a delete method.
Objects are serialized using Marshal, so it’s very
fast.
@tags = Tag.find_all
Cache.put 'all_your_tags', @tags
Cache.put 'favorite_skateboarder', 'Tom Penny'
skateboarder = Cache.get 'favorite_skateboarder'
Cache.delete 'all_your_tags'