通过Heroku上的ruby daemon worker拒绝Redis连接

时间:2012-07-10 12:56:38

标签: ruby-on-rails ruby heroku redis worker

作为'web'运行的Rails 3.2.6应用程序Heroku进程使用ENV [“REDISTOGO_URL”]环境变量连接到Redis:

irb(main):002:0> Redis.current
=> #<Redis client v2.2.2 connected to redis://xxx.redistogo.com:1234/0 (Redis v2.4.11)>

----- /initializers/redis.rb

if Rails.env.development?
  Redis.current = Redis.new
elsif Rails.env.test?
  Redis.current = Redis.new
elsif Rails.env.production?
  uri = URI.parse(ENV["REDISTOGO_URL"])
  Redis.current = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
end

ruby​​守护程序'streaming'流程作为辅助工作程序运行:

----- Procfile

web: bundle exec rails server thin -p $PORT -e $RACK_ENV
worker: bundle exec rake jobs:work
streaming: RAILS_ENV=production ruby bin/streaming.rb start

然而,当流程进程调用与Redis连接的主Rails应用程序中的方法时,流程正在崩溃 - 即使流式处理过程应该加载与'web'Rails应用程序进程相同的redis.rb初始化程序。

----- /bin/streaming_ctl.rb

# encoding: UTF-8

require "rubygems"
require "bundler/setup"
require "daemons"

Daemons.run(File.expand_path("../streaming.rb", __FILE__))

----- /bin/streaming.rb

# encoding: UTF-8

# TODO: set rails env in init script
ENV["RAILS_ENV"] ||= "production"

# load rails environment
require File.expand_path('../../config/environment', __FILE__)

logger = ActiveSupport::BufferedLogger.new(File.expand_path("./../../log/streaming.log", __FILE__))

Streaming.start
logger.info("\nStarting streaming in #{Rails.env.to_s} mode.")

为什么流媒体进程/工作人员使用默认的Redis主机和端口?

[streaming.1]: /app/vendor/bundle/ruby/1.9.1/gems/redis-2.2.2/lib/redis/client.rb:236:in `rescue in establish_connection': Connection refused - Unable to connect to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)

1 个答案:

答案 0 :(得分:1)

从/initializer/redis.rb中的“Redis.current”切换并使用“$ redis”变量约定(如此处http://jimneath.org/2011/03/24/using-redis-with-ruby-on-rails.html所示)修复了连接问题。

该应用当时正在使用redis gem 2.2.2版。看起来好像这个gem版本中的Redis.current在'web'和'worker'进程中不一致,因为Heroku在不同的线程上运行这些进程。 gem repo上的文档表明,将gem更新为&gt; =版本3将使Redis.current能够在多线程环境中运行:

https://github.com/redis/redis-rb/blob/master/CHANGELOG.md#300