I am using redis as a read cache. I have created an initializer
config/initializer/redis.rb
$redis = Redis.new(:host => ENV[\"REDIS_HOST\"], :port =&
expanding further on mestachs suggestion, namespacing a module in your initializer as below
config/initializers/redis.rb
module ReadCache
class << self
def redis
@redis ||= Redis.new(:url => (ENV["REDIS_URL"] || 'redis://127.0.0.1:6379'))
end
end
end
then in unicorn.rb
before_fork do |server, worker|
...
if defined?(ReadCache.redis)
ReadCache.redis.quit
end
...
end
after_fork do |server, worker|
...
if defined?(ReadCache.redis)
ReadCache.redis.client.reconnect
end
...
end
There is Redis.current
, which you can use to store your one-and-only Redis
instance.
So instead of using $redis
, you can assign your instance as follows:
Redis.current = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])
Redis.current
was introduced to redis-rb in 2010 as a standard way to grab a redis connection, so I was surprised that no other answer mentioned it.
if you don't already use another Rails.cache I advise you to just use that mechanism with redis.
The gem redis-store makes this realy easy (https://github.com/redis-store/redis-store)
This way you can just do Rails.cache.reconnect
and all is dandy
https://github.com/redis-store/redis-store/issues/21#issuecomment-948569
It also allows you to use the awesome Rails.cache API, which has some neat features: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html
According to this Heroku, you don't need to add $redis
to your Unicorn:
No special setup is required when using Redis Cloud with a Unicorn server. Users running Rails apps on Unicorn should follow the instructions in the Configuring Redis from Rails section and users...
Here's all the "Configuring Redis from Rails section" has for before Rails 4 (besides the Gemfile and some other pre-Rails 3 stuff):
# config/initalizers/redis.rb
if ENV["REDISCLOUD_URL"]
uri = URI.parse(ENV["REDISCLOUD_URL"])
$redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
end
It doesn't really give an explanation as to why "no special setup is required".
A more namespaced option to replace your global variable, you can create a method in a module
module Caching def self.redis ... initialize/memoize/reconnect here... end end
You than then call it with:
Caching.redis
try this out:-
you can use constant
instead of global variable
.like in
config/initializer/redis.rb
REDIS = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])
and in unicorn.rb
before_fork do |server, worker|
# clear redis connection
REDIS.quit if defined?(REDIS)
end
# Give each child process its own Redis connection
after_fork do |server, worker|
REDIS ||= Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])
end