ruby – 无法挽救Redis连接拒绝

前端之家收集整理的这篇文章主要介绍了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"

救援块永远不会被执行,而是引发异常.这是此脚本的输出.

/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”)按预期工作.通过使用救援Errno :: ECONNREFUSED无济于事,我试图通过我的救援块更加具体.我不知道为什么我不能抓住这个例外.

有任何想法吗?

解决方法

事实证明,在调用Redis.new时不会抛出异常.在调用连接对象上的某些方法(在本例中为Redis#键)之前,不会抛出异常.这个修改过的连接函数似乎可以解决问题.
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
原文链接:https://www.f2er.com/ruby/268275.html

猜你在找的Ruby相关文章