$redis global variable with ruby on rails $redis global variable with ruby on rails ruby ruby

$redis global variable with ruby on rails


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.


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  endend

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


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