$redis 全局变量与 ruby​​ on rails [英] $redis global variable with ruby on rails

查看:52
本文介绍了$redis 全局变量与 ruby​​ on rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 redis 作为读取缓存.我已经创建了一个初始化程序

I am using redis as a read cache. I have created an initializer

config/initializer/redis.rb

config/initializer/redis.rb

$redis = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])

我在我的 unicorn.rb 中使用这个全局变量来创建一个新的连接.

I am using this global in my unicorn.rb to create a new connection whenever a new worker is created.

before_fork do |server, worker|
  # clear redis connection
  $redis.quit unless $redis.blank?
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

每当我需要访问我的 redis 服务器时,我也会使用这个全局变量.但是我不习惯使用这个全局变量.还有比使用全局变量更好的选择吗?

I am also using this global variable whenever I need to access my redis servers. But I am not comfortable using this global variable. Are there any better options than using global variable?

推荐答案

进一步扩展 mestachs 建议,在你的初始化器中命名一个模块如下

expanding further on mestachs suggestion, namespacing a module in your initializer as below

config/initializers/redis.rb

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

然后在 unicorn.rb

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

这篇关于$redis 全局变量与 ruby​​ on rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆