$redis global variable with ruby on rails

后端 未结 6 612
灰色年华
灰色年华 2021-02-01 14:35

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 =&         


        
6条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 15:11

    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
    

提交回复
热议问题