Class: EventMachine::Hiredis::BaseClient

Inherits:
Object
  • Object
show all
Includes:
EM::Deferrable, EventEmitter
Defined in:
lib/em-hiredis/base_client.rb

Overview

Emits the following events

  • :connected - on successful connection or reconnection

  • :reconnected - on successful reconnection

  • :disconnected - no longer connected, when previously in connected state

  • :reconnect_failed(failure_number) - a reconnect attempt failed

    This event is passed number of failures so far (1,2,3...)
    
  • :monitor

Direct Known Subclasses

Client, PubsubClient

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from EventEmitter

#emit, #listeners, #on, #remove_all_listeners, #remove_listener

Constructor Details

#initialize(host = 'localhost', port = 6379, password = nil, db = nil) ⇒ BaseClient

Returns a new instance of BaseClient.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/em-hiredis/base_client.rb', line 19

def initialize(host = 'localhost', port = 6379, password = nil, db = nil)
  @host, @port, @password, @db = host, port, password, db
  @defs = []
  @command_queue = []

  @reconnect_failed_count = 0
  @reconnect_timer = nil
  @failed = false

  self.on(:failed) {
    @failed = true
    @command_queue.each do |df, _, _|
      df.fail(Error.new("Redis connection in failed state"))
    end
    @command_queue = []
  }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object (private)



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/em-hiredis/base_client.rb', line 186

def method_missing(sym, *args)
  deferred = EM::DefaultDeferrable.new
  # Shortcut for defining the callback case with just a block
  deferred.callback { |result| yield(result) } if block_given?

  if @connected
    @connection.send_command(sym, args)
    @defs.push(deferred)
  elsif @failed
    deferred.fail(Error.new("Redis connection in failed state"))
  else
    @command_queue << [deferred, sym, args]
  end

  deferred
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



17
18
19
# File 'lib/em-hiredis/base_client.rb', line 17

def db
  @db
end

#hostObject (readonly)

Returns the value of attribute host.



17
18
19
# File 'lib/em-hiredis/base_client.rb', line 17

def host
  @host
end

#passwordObject (readonly)

Returns the value of attribute password.



17
18
19
# File 'lib/em-hiredis/base_client.rb', line 17

def password
  @password
end

#portObject (readonly)

Returns the value of attribute port.



17
18
19
# File 'lib/em-hiredis/base_client.rb', line 17

def port
  @port
end

Instance Method Details

#auth(password, &blk) ⇒ Object



165
166
167
168
# File 'lib/em-hiredis/base_client.rb', line 165

def auth(password, &blk)
  @password = password
  method_missing(:auth, password, &blk)
end

#close_connectionObject



170
171
172
173
174
# File 'lib/em-hiredis/base_client.rb', line 170

def close_connection
  EM.cancel_timer(@reconnect_timer) if @reconnect_timer
  @auto_reconnect = false
  @connection.close_connection_after_writing
end

#configure(uri_string) ⇒ Object

Configure the redis connection to use

In usual operation, the uri should be passed to initialize. This method is useful for example when failing over to a slave connection at runtime



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/em-hiredis/base_client.rb', line 42

def configure(uri_string)
  uri = URI(uri_string)

  if uri.scheme == "unix"
    @host = uri.path
    @port = nil
  else
    @host = uri.host
    @port = uri.port
    @password = uri.password
    path = uri.path[1..-1]
    @db = path.to_i # Empty path => 0
  end
end

#connectObject



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/em-hiredis/base_client.rb', line 70

def connect
  @auto_reconnect = true
  @connection = EM.connect(@host, @port, Connection, @host, @port)

  @connection.on(:closed) do
    if @connected
      @defs.each { |d| d.fail(Error.new("Redis disconnected")) }
      @defs = []
      @deferred_status = nil
      @connected = false
      if @auto_reconnect
        # Next tick avoids reconnecting after for example EM.stop
        EM.next_tick { reconnect }
      end
      emit(:disconnected)
      EM::Hiredis.logger.info("#{@connection} Disconnected")
    else
      if @auto_reconnect
        @reconnect_failed_count += 1
        @reconnect_timer = EM.add_timer(EM::Hiredis.reconnect_timeout) {
          @reconnect_timer = nil
          reconnect
        }
        emit(:reconnect_failed, @reconnect_failed_count)
        EM::Hiredis.logger.info("#{@connection} Reconnect failed")

        if @reconnect_failed_count >= 4
          emit(:failed)
          self.fail(Error.new("Could not connect after 4 attempts"))
        end
      end
    end
  end

  @connection.on(:connected) do
    @connected = true
    @reconnect_failed_count = 0
    @failed = false

    select(@db) unless @db == 0
    auth(@password) if @password

    @command_queue.each do |df, command, args|
      @connection.send_command(command, args)
      @defs.push(df)
    end
    @command_queue = []

    emit(:connected)
    EM::Hiredis.logger.info("#{@connection} Connected")
    succeed

    if @reconnecting
      @reconnecting = false
      emit(:reconnected)
    end
  end

  @connection.on(:message) do |reply|
    if RuntimeError === reply
      raise "Replies out of sync: #{reply.inspect}" if @defs.empty?
      deferred = @defs.shift
      error = RedisError.new(reply.message)
      error.redis_error = reply
      deferred.fail(error) if deferred
    else
      handle_reply(reply)
    end
  end

  @connected = false
  @reconnecting = false

  return self
end

#connected?Boolean

Returns:

  • (Boolean)


156
157
158
# File 'lib/em-hiredis/base_client.rb', line 156

def connected?
  @connected
end

#pending_commands?Boolean

Indicates that commands have been sent to redis but a reply has not yet been received

This can be useful for example to avoid stopping the eventmachine reactor while there are outstanding commands

Returns:

  • (Boolean)


152
153
154
# File 'lib/em-hiredis/base_client.rb', line 152

def pending_commands?
  @connected && @defs.size > 0
end

#reconnect!(new_uri = nil) ⇒ Object

Disconnect then reconnect the redis connection.

Pass optional uri - e.g. to connect to a different redis server. Any pending redis commands will be failed, but during the reconnection new commands will be queued and sent after connected.



63
64
65
66
67
68
# File 'lib/em-hiredis/base_client.rb', line 63

def reconnect!(new_uri = nil)
  @connection.close_connection
  configure(new_uri) if new_uri
  @auto_reconnect = true
  EM.next_tick { reconnect_connection }
end

#reconnect_connectionObject

Note: This method doesn’t disconnect if already connected. You probably want to use ‘reconnect!`



178
179
180
181
182
# File 'lib/em-hiredis/base_client.rb', line 178

def reconnect_connection
  @auto_reconnect = true
  EM.cancel_timer(@reconnect_timer) if @reconnect_timer
  reconnect
end

#select(db, &blk) ⇒ Object



160
161
162
163
# File 'lib/em-hiredis/base_client.rb', line 160

def select(db, &blk)
  @db = db
  method_missing(:select, db, &blk)
end