Caching is a process of storing data generated by new requests in order to serve similar requests in the future more swiftly. When developing a web-application, caching serves as an essential tool to manage requests and speed-up the response time. Through caching, web sites running on a single server with a single database can sustain a load of thousands of concurrent users.
Memcache is one of the different caching systems. Memcache caches objects in RAM to speed up access to the content. Content is directly fetched from memory instead of from an external data source. One of the most popular memcache servers is provided by Danga, an open-source software.
Ruby on Rails uses the Danga server coupled with
This installation setup is for Ubuntu.
Use the following command to install memcache:
sudo apt install memcached
If you already have rubygems installed on your system, skip this step. Otherwise, install rubygems using the follwing command:
sudo apt-get install rubygems
Install Dalli using the following command:
sudo gem install dalli
After that, add the following: line in your gemfile:
gem 'dalli'
Finally, execute this command:
bundle install
In order to open up a connection to memcache using Dalli, use the following dummy code:
require 'dalli'
options = { :username => 'username', :password => 'password' }
mc = Dalli::Client.new('hostname:port', options)
To make this snippet of code compatible with your code, change :username
, :password
, and hostname:port
according to the variables in your bucket.
Reading and writing data on memcache is straight forward. Observe the following code snippet:
mc.set('drink', 'tea')
value = mc.get('drink')
puts value
The above code will store key-value pairs in memcache. The key is drink and it has a value of tea. Use the .set()
method to place a key-value pair on memcache and use the .get()
method to retrieve a value using a key from the memcache.
Free Resources