]>
git.saurik.com Git - redis.git/blob - client-libraries/ruby/lib/server.rb
4fb54937fb1d7cbecb7926e78b9e76de1e95956b
2 # Timeout code is courtesy of Ruby memcache-client
3 # http://github.com/mperham/memcache-client/tree
4 # Try to use the SystemTimer gem instead of Ruby's timeout library
5 # when running on something that looks like Ruby 1.8.x. See:
6 # http://ph7spot.com/articles/system_timer
7 # We don't want to bother trying to load SystemTimer on jruby and
9 if defined?(JRUBY_VERSION
) || (RUBY_VERSION >= '1.9')
13 require 'system_timer'
14 RedisTimer
= SystemTimer
17 puts
"[redis-rb] Could not load SystemTimer gem, falling back to Ruby's slower/unsafe timeout library: #{e.message}"
23 # This class represents a redis server instance.
28 # The host the redis server is running on.
33 # The port the redis server is listening on.
38 # A text status string describing the state of the server.
43 # Create a new Redis::Server object for the redis instance
44 # listening on the given host and port.
46 def initialize(host
, port
= DEFAULT_PORT
, timeout
= 10)
47 raise ArgumentError
, "No host specified" if host
.nil? or host
.empty
?
48 raise ArgumentError
, "No port specified" if port
.nil? or port
.to_i
.zero
?
54 @status = 'NOT CONNECTED'
59 # Return a string representation of the server object.
61 "<Redis::Server: %s:%d (%s)>" % [@host, @port, @status]
65 # Try to connect to the redis server targeted by this object.
66 # Returns the connected socket object on success or nil on failure.
69 return @sock if socket_alive
?
71 # Attempt to connect if not already connected.
73 @sock = connect_to(@host, @port, @timeout)
74 @sock.setsockopt Socket
::IPPROTO_TCP, Socket
::TCP_NODELAY, 1
76 rescue Errno
::EPIPE, Errno
::ECONNREFUSED => e
77 puts
"Socket died... : #{e}\n" if $debug
79 rescue SocketError
, SystemCallError
, IOError
=> err
80 puts
"Unable to open socket: #{err.class.name}, #{err.message}" if $debug
85 def connect_to(host
, port
, timeout
=nil)
86 socket
= TCPSocket
.new(host
, port
)
87 socket
.set_encoding(Encoding
::BINARY) if socket
.respond_to
?(:set_encoding)
89 socket
.instance_eval
<<-EOR
90 alias :blocking_readline :readline
92 RedisTimer.timeout(#{timeout}) do
93 self.blocking_readline(*args)
96 alias :blocking_read :read
98 RedisTimer.timeout(#{timeout}) do
99 self.blocking_read(*args)
102 alias :blocking_write :write
104 RedisTimer.timeout(#{timeout}) do
105 self.blocking_write(*args)
113 # Close the connection to the redis server targeted by this
117 @sock.close
if !
@sock.nil? && !
@sock.closed
?
119 @status = "NOT CONNECTED"
124 #BTM - TODO - FileStat is borked under JRuby
125 unless defined?(JRUBY_VERSION
)
126 !
@sock.nil? && !
@sock.closed
? && @sock.stat
.readable
?
128 !
@sock.nil? && !
@sock.closed
?