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:

# Redis stores
gem 'redis-rails'

Let’s execute bundle install on your terminal.

πŸŽƒ Usage

Add the following to your environment variable or .env:

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

Configure to use Redis for cache store is as follows:

# 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:

# 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:

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

Happy Hacking!

πŸ€ Special Thanks

πŸ–₯ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!