我使用redis作为读缓存.我创建了一个初始值设定项

config/initializer/redis.rb

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

我在我的独角兽身上使用这个全球定位系统.rb在创建新工作进程时创建新连接.

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服务器时,我也会使用这个全局变量.但我不喜欢使用这个全局变量.有比使用全局变量更好的 Select 吗?

推荐答案

进一步扩展mestachs的建议,在初始值设定项中命名模块,如下所示

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

然后是独角兽.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

Ruby-on-rails相关问答推荐

Ubuntu Webhooks无法读取安装的正确RVM Ruby

链轮轨道V4链接到外部Ruby 的 list 文件

多对多模型通过控制台创建记录不起作用

如何从 Rails7.2 中的控制器获取名称空间?

为什么在使用 Ruby on Rails 时我的徽标没有出现在 Bootstrap 导航栏中?

Rails Scope 返回 all 而不是 nil

无法连接 localhost:3000 ruby​​ on rails in vagrant

在 Rails 中将毫秒转换为格式化日期

将 Amazon SES 与 Rails ActionMailer 结合使用

升级到设计 3.1 => 获取重置密码令牌无效

奇怪的406 不可接受错误

如何在 Rails 中验证日期以使其在今天之后?

Ruby on Rails 中的MySQL 服务器已经消失

通过 Ruby 或 Rails 的 LDAP

如何仅使用 PostgreSQL 创建简单的模糊搜索?

如何在 Ruby 中搜索数组?

通过get in rails传递参数数组

在任何来源中都找不到 thread_safe-0.3.0

Sidekiq Rails 4.2 使用 Active Job 还是 Worker?有什么不同

使用设计创建一个用户显示页面