How to Use Redis for Caching in Ruby on Rails
To use
Redis for caching in Ruby on Rails, configure Rails to use redis_cache_store by setting config.cache_store = :redis_cache_store with your Redis server URL in config/environments/production.rb. Then use Rails caching methods like Rails.cache.fetch to store and retrieve cached data efficiently.Syntax
To enable Redis caching in Rails, set the cache store in your environment configuration file. The key parts are:
config.cache_store: tells Rails which cache backend to use.:redis_cache_store: the Redis adapter for caching.url: the Redis server address.
Example syntax:
ruby
config.cache_store = :redis_cache_store, { url: 'redis://localhost:6379/1' }Example
This example shows how to configure Redis caching in config/environments/production.rb and how to cache a value in a controller using Rails.cache.fetch. The cached value is stored in Redis and reused until it expires.
ruby
Rails.application.configure do
# Use Redis as cache store
config.cache_store = :redis_cache_store, { url: ENV.fetch('REDIS_URL') { 'redis://localhost:6379/1' } }
end
class ProductsController < ApplicationController
def index
@products = Rails.cache.fetch('products_all', expires_in: 12.hours) do
Product.all.to_a
end
render json: @products
end
endOutput
[{"id":1,"name":"Product A"},{"id":2,"name":"Product B"}, ...]
Common Pitfalls
Common mistakes when using Redis caching in Rails include:
- Not setting the Redis URL correctly, causing connection errors.
- Forgetting to set
expires_in, which can lead to stale cache data. - Using Redis for caching without running a Redis server.
- Not enabling caching in development environment, so cache calls seem ineffective.
Example of a wrong and right cache fetch usage:
ruby
# Wrong: No expiration, cache might never refresh Rails.cache.fetch('key') { expensive_operation } # Right: Set expiration to refresh cache periodically Rails.cache.fetch('key', expires_in: 1.hour) { expensive_operation }
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Set cache store | config.cache_store = :redis_cache_store, { url: 'redis://localhost:6379/1' } | Configure Redis URL and DB index |
| Cache fetch | Rails.cache.fetch('key', expires_in: 1.hour) { block } | Caches block result with expiration |
| Clear cache | Rails.cache.delete('key') | Removes cached data by key |
| Check cache | Rails.cache.exist?('key') | Returns true if key exists in cache |
Key Takeaways
Configure Redis as the cache store in Rails environment files using :redis_cache_store.
Use Rails.cache.fetch with an expiration time to store and retrieve cached data safely.
Ensure Redis server is running and accessible at the configured URL.
Set cache expiration to avoid stale data and memory bloat.
Enable caching in the environment to see Redis caching effects.