无法挽救Redis连接拒绝

时间:2011-10-05 07:14:59

标签: ruby redis

我正在尝试编写一个尝试使用默认TCP设置连接到Redis的函数,如果失败,则尝试通过unix套接字连接到Redis。我的意图是有一个适用于我所有系统的连接脚本,其中一些使用TCP,另一些使用套接字。

但是,我似乎无法从失败的TCP连接中解救出来。这是我的测试脚本。

require "redis"

def r
  begin
    $redis ||= Redis.new
  rescue
    $redis = Redis.new(:path => "/tmp/redis.sock")
  end
end

puts "You have #{r.keys.count} redis keys"

rescue块永远不会被执行,而是引发异常。以下是此脚本的输出。

/usr/local/rvm/gems/ruby-1.9.2-p290/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)
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis/client.rb:222:in `establish_connection'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis/client.rb:23:in `connect'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis/client.rb:247:in `ensure_connected'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis/client.rb:137:in `block in process'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis/client.rb:206:in `logging'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis/client.rb:136:in `process'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis/client.rb:46:in `call'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis.rb:246:in `block in keys'
    from /usr/local/rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
    from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/redis-2.2.2/lib/redis.rb:245:in `keys'
    from scripts/redis.rb:11:in `<main>'

我已经确认Redis.new(:path => "/tmp/redis.sock")按预期工作。我试图通过rescue Errno::ECONNREFUSED使用我的救援块更具体,但无济于事。我不知道为什么我不能抓住这个例外。

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

事实证明,在调用Redis.new时不会抛出异常。在调用连接对象上的某些方法(在本例中为Redis#keys)之前,不会抛出异常。这个修改过的连接函数似乎可以解决问题。

require "redis"

def r
  begin
    $redis ||= Redis.new
    $redis.inspect # needed to know if connection failed
  rescue
    $redis = Redis.new(:path => "/tmp/redis.sock")
  end
  $redis
end

答案 1 :(得分:2)

我发现$redis.inspect实际上没有REDIS连接。我将其替换为$redis.keys并正确抛出异常。请注意,我正在Heroko上运行并传入环境变量REDISTOGO_URL。然后,我在整个应用程序中使用了一个常量REDIS

在我的config / initializers / redis.rb中:

uri = URI.parse(ENV['REDISTOGO_URL'])
begin
  redis ||= Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
  redis.keys # needed to know if connection failed
  REDIS = redis
rescue
  puts("Redis not loaded on #{uri.port}")
  REDIS = nil
end