We are now, simply, Redis

Learn More

Rails Memcached

Make Rails Memcached super easy with Redis Enterprise

Using Memcached with Ruby

In order to use Memcached with Ruby you will need a Ruby Memcached client. In the following sections, we will demonstrate the use of dalli, a high-performance memcached client for Ruby.

Installing Dalli

Dalli’s installation instructions are given in the “Installation and usage” section of its README file. After installing memcached, use gem to install Dalli:

foo@bar:~$ gem install dalli

Or, include dalli in your Gemfile by adding the following line:

gem 'dalli'

Followed by executing bundle install.

Opening a Connection to Memcached Using Dalli

The following code creates a connection to Memcached using Dalli:

require 'dalli'

options = { :username => 'username', :password => 'password' }
mc = Dalli::Client.new('hostname:port', options)

To adapt this example to your code, make sure that you replace the following values with those of your bucket:

Reading and Writing Data with Dalli

Once connected to Memcached, you can start reading and writing data. The following code snippet writes the value bar to the Memcached key foo, reads it back, and prints it:

# open a connection to Memcached

mc.set('foo', 'bar')
value = mc.get('foo')
puts value

The output of the above code should be:

$ ruby example_dalli.rb

Using Dalli with Rails 3 and 4

To use Memcached as a cache store for Rails, modify the file config/environments/production.rb with the following:

config.cache_store = :dalli_store,
                {:username => 'username',
                 :password => 'password'

Once configured, you can use the following snippet to use the cache in your Rails app:

Rails.cache.write("foo", "bar")
value = Rails.cache.read("foo")

Redis Enterprise enables running Memcached buckets in a highly available and auto-scalable manner, with predictable top performance.

Redis Enterprise Software lets you install an enterprise grade Memcached cluster in your environment of choice, whether an on-premises data-center or your preferred cloud platform. It gives you full control of your data and configuration – no clustering or sharding knowledge required!

Memcached Cloud is a fully managed cloud service for hosting and running Memcached datasets in a highly available and scalable manner, with predictable and stable top performance. It provides a storage engine for standard Memcached, as well as in-memory replication and instant auto-failover within the same data center or across data centers. The service completely frees developers from dealing with nodes, clusters, scaling, data persistence issues or failure recovery.

For more information on using Redis’ products and services with ruby please see the Howto page.