redis-rb: checking to see if connection was successfully established

4,409 views
Skip to first unread message

Keith

unread,
Oct 28, 2010, 12:35:07 PM10/28/10
to Redis DB
Hi all,

Does anyone know how I can check to see if the Redis Ruby client is
able to establish a connection?

For example, if the Redis server is currently turned unavailable, I
want to be able to detect that display a messge to the user:

require 'rubygems'
require 'redis'

begin
print "Connecting to Redis...\n"
r = Redis.new
rescue Errno::ECONNREFUSED=>e
print "Error: Redis server unavailable. Shutting down..."
exit 1
end

When I try the same code in irb, I can see the exception being thrown,
but I still cannot rescue it:

begin
irb(main):031:1* r=Redis.new
irb(main):032:1> rescue Exception=>e
irb(main):033:1> print "Caught it!"
irb(main):034:1> end
Errno::ECONNREFUSED: Connection refused - Unable to connect to Redis
on 127.0.0.1:6379
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis/client.rb:228:in
`connect_to'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis/client.rb:23:in
`connect'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis/client.rb:244:in
`ensure_connected'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis/client.rb:63:in
`process'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis/client.rb:201:in
`logging'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis/client.rb:62:in
`process'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis/client.rb:34:in
`call'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis.rb:65:in `info'
from /var/lib/gems/1.8/gems/redis-2.0.12/lib/redis.rb:606:in
`inspect'
from /usr/lib/ruby/1.8/irb.rb:310:in `output_value'
from /usr/lib/ruby/1.8/irb.rb:159:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:271:in `signal_status'
from /usr/lib/ruby/1.8/irb.rb:155:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:154:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:71:in `start'
from /usr/lib/ruby/1.8/irb.rb:70:in `catch'
from /usr/lib/ruby/1.8/irb.rb:70:in `start'
from /usr/bin/irb:13irb(main):035:0>

Any suggestions?

Thanks!

Damian Janowski

unread,
Oct 28, 2010, 1:20:59 PM10/28/10
to redi...@googlegroups.com

The Ruby client establishes the connection lazily – ie, whenever it
really needs it.

In this case, you're creating a new instance without issuing any
commands, and that's why you're not able to rescue the exception. In
your IRB session, once the begin/end block is evaluated, the return
value is the instance of the Redis class. IRB is trying to call
`inspect` on it, and that's when the client is trying to establish the
connection.

In short:

begin
puts "Connecting to Redis..."
r = Redis.new
r.ping
rescue Errno::ECONNREFUSED => e
puts "Error: Redis server unavailable. Shutting down..."
exit 1
end

Reply all
Reply to author
Forward
0 new messages