Gem of the Week: Dalli
August 4, 2016 Jamey Alea 0 Comments
If the question is how to support good performance for high volume requests without bogging down your database, the answer is caching. Caching data is a powerful tool in any programmer’s arsenal when it comes to speeding up websites and making information easier and faster to access. However, it can be tricky to pull off correctly. Dalli is a very handy gem which is cleverly named after Salvador Dali’s famous painting, the Persistence of Memory. It integrates with Memcached to make caching easy and painless for Rails developers.
Dalli is a neat little memcached client that doesn’t require any runtime dependencies and is easy to install and configure. Once it’s in your gemfile, you just have to specify the cache store in your config files that live in the config/environment folder.
Here’s what I have in my config/environment/development.rb file:
config.action_controller.perform_caching = true config.cache_store = :dalli_store, 'localhost:11211', { :namespace => NAME_OF_RAILS_APP, :compress => true }
The options hash can also take an “expires_in” option that will set a default for when your cache entries should expire. Each time you store something in the cache, you can set an expiration time individually, but if you don’t, it will default back to what you set here. Or, as in my example, you can not set a default and your cache entries won’t expire automatically.
You also have to make sure you have memcached installed on your machine and run it using the command
memcached -vv
This is literally all you need to do to get started using the cache in your code. Write items to the cache and then retrieve them like this.
Rails.cache.write(“keyword”, “value”, :expires_in => 3600) Rails.cache.fetch(“keyword”)
If there is already data stored in the cache using a certain keyword, using the write method will overwrite it. If you want to conditionally store something only if the keyword is already free without overwriting, you can do it like this:
Rails.cache.fetch(“keyword”, :expires_in => 3600) do “value2” end
If there’s already data stored under “keyword”, it will be preserved and the value will NOT be set to “value2.”
Those are the basics, but there is so much more that Memcached and Dalli can do. For instance, Dalli is also configured to work with multithreading and can be configured to take options for pool size.
Visit the full API for Rails.cache here
Visit the Github page for Dalli here if you want to see the rest of the configuration options
Deciding to implement caching in your app isn’t one to be taken lightly and the underlying architecture should be given careful consideration. However, if you decide to do it, using the Dalli / Memcached combo should make the implementation the least of your worries.
(This article was originally published on Uptime.)