Using Redis for caching & session management with Ruby on Rails

This article shows about cacing data & session management with Ruby on Rails.


Installation

Add the following “redis-rails“ to your Gemfile:

1
2
# Redis stores
gem 'redis-rails'

Let’s execute bundle install on your terminal.

Usage

Add the following to your environment variable or .env:

1
REDIS_URL="redis://localhost:6379/0/cache"

Configure to use Redis for cache store is as follows:

1
2
3
# config/application.rb
# expires_in is optional
config.cache_store = :redis_store, ENV.fetch('REDIS_URL'), { expires_in: 90.minutes }

If you want to use Redis as a backend for sessions, you should also set:

1
2
# config/initializers/session_store.rb
MyApplication::Application.config.session_store :redis_store, servers: "redis://localhost:6379/0/session"

If you want to skip to cache on TEST environment, please set NullStore:

1
2
# config/environments/test.rb:
config.cache_store = :null_store

Happy Hacking!

Special Thanks