Class: Redis::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/redis/client.rb

Defined Under Namespace

Classes: Connector

Constant Summary collapse

DEFAULTS =

Defaults are also used for converting string keys to symbols.

{
  url: -> { ENV["REDIS_URL"] },
  scheme: "redis",
  host: "127.0.0.1",
  port: 6379,
  path: nil,
  read_timeout: nil,
  write_timeout: nil,
  connect_timeout: nil,
  timeout: 5.0,
  username: nil,
  password: nil,
  db: 0,
  driver: nil,
  id: nil,
  tcp_keepalive: 0,
  reconnect_attempts: 1,
  reconnect_delay: 0,
  reconnect_delay_max: 0.5,
  inherit_socket: false,
  logger: nil,
  sentinels: nil,
  role: nil
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/redis/client.rb', line 93

def initialize(options = {})
  @options = _parse_options(options)
  @reconnect = true
  @logger = @options[:logger]
  @connection = nil
  @command_map = {}

  @pending_reads = 0

  @connector =
    if !@options[:sentinels].nil?
      Connector::Sentinel.new(@options)
    elsif options.include?(:connector) && options[:connector].respond_to?(:new)
      options.delete(:connector).new(@options)
    else
      Connector.new(@options)
    end
end

Instance Attribute Details

#command_mapObject (readonly)

Returns the value of attribute command_map.



91
92
93
# File 'lib/redis/client.rb', line 91

def command_map
  @command_map
end

#connectionObject (readonly)

Returns the value of attribute connection.



90
91
92
# File 'lib/redis/client.rb', line 90

def connection
  @connection
end

#loggerObject

Returns the value of attribute logger.



89
90
91
# File 'lib/redis/client.rb', line 89

def logger
  @logger
end

#optionsObject (readonly)

Returns the value of attribute options.



35
36
37
# File 'lib/redis/client.rb', line 35

def options
  @options
end

Instance Method Details

#call(command) ⇒ Object



161
162
163
164
165
166
167
168
169
170
# File 'lib/redis/client.rb', line 161

def call(command)
  reply = process([command]) { read }
  raise reply if reply.is_a?(CommandError)

  if block_given? && reply != 'QUEUED'
    yield reply
  else
    reply
  end
end

#call_loop(command, timeout = 0) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/redis/client.rb', line 172

def call_loop(command, timeout = 0)
  error = nil

  result = with_socket_timeout(timeout) do
    process([command]) do
      loop do
        reply = read
        if reply.is_a?(CommandError)
          error = reply
          break
        else
          yield reply
        end
      end
    end
  end

  # Raise error when previous block broke out of the loop.
  raise error if error

  # Result is set to the value that the provided block used to break.
  result
end

#call_pipeline(pipeline) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/redis/client.rb', line 196

def call_pipeline(pipeline)
  return [] if pipeline.futures.empty?

  with_reconnect pipeline.with_reconnect? do
    begin
      pipeline.finish(call_pipelined(pipeline)).tap do
        self.db = pipeline.db if pipeline.db
      end
    rescue ConnectionError => e
      return nil if pipeline.shutdown?

      # Assume the pipeline was sent in one piece, but execution of
      # SHUTDOWN caused none of the replies for commands that were executed
      # prior to it from coming back around.
      raise e
    end
  end
end

#call_pipelined(pipeline) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/redis/client.rb', line 215

def call_pipelined(pipeline)
  return [] if pipeline.futures.empty?

  # The method #ensure_connected (called from #process) reconnects once on
  # I/O errors. To make an effort in making sure that commands are not
  # executed more than once, only allow reconnection before the first reply
  # has been read. When an error occurs after the first reply has been
  # read, retrying would re-execute the entire pipeline, thus re-issuing
  # already successfully executed commands. To circumvent this, don't retry
  # after the first reply has been read successfully.

  commands = pipeline.commands

  result = Array.new(commands.size)
  reconnect = @reconnect

  begin
    exception = nil

    process(commands) do
      pipeline.timeouts.each_with_index do |timeout, i|
        reply = if timeout
          with_socket_timeout(timeout) { read }
        else
          read
        end
        result[i] = reply
        @reconnect = false
        exception = reply if exception.nil? && reply.is_a?(CommandError)
      end
    end

    raise exception if exception
  ensure
    @reconnect = reconnect
  end

  result
end

#call_with_timeout(command, timeout, &blk) ⇒ Object



255
256
257
258
259
260
261
# File 'lib/redis/client.rb', line 255

def call_with_timeout(command, timeout, &blk)
  with_socket_timeout(timeout) do
    call(command, &blk)
  end
rescue ConnectionError
  retry
end

#call_without_timeout(command, &blk) ⇒ Object



263
264
265
# File 'lib/redis/client.rb', line 263

def call_without_timeout(command, &blk)
  call_with_timeout(command, 0, &blk)
end

#connectObject



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
145
146
147
148
149
150
151
# File 'lib/redis/client.rb', line 112

def connect
  @pid = Process.pid

  # Don't try to reconnect when the connection is fresh
  with_reconnect(false) do
    establish_connection
    if password
      if username
        begin
          call [:auth, username, password]
        rescue CommandError => err # Likely on Redis < 6
          if err.message.match?(/ERR wrong number of arguments for \'auth\' command/)
            call [:auth, password]
          elsif err.message.match?(/WRONGPASS invalid username-password pair/)
            begin
              call [:auth, password]
            rescue CommandError
              raise err
            end
            ::Kernel.warn(
              "[redis-rb] The Redis connection was configured with username #{username.inspect}, but" \
              " the provided password was for the default user. This will start failing in redis-rb 4.6."
            )
          else
            raise
          end
        end
      else
        call [:auth, password]
      end
    end

    call [:readonly] if @options[:readonly]
    call [:select, db] if db != 0
    call [:client, :setname, @options[:id]] if @options[:id]
    @connector.check(self)
  end

  self
end

#connect_timeoutObject



57
58
59
# File 'lib/redis/client.rb', line 57

def connect_timeout
  @options[:connect_timeout]
end

#connected?Boolean

Returns:

  • (Boolean)


284
285
286
# File 'lib/redis/client.rb', line 284

def connected?
  !!(connection && connection.connected?)
end

#dbObject



73
74
75
# File 'lib/redis/client.rb', line 73

def db
  @options[:db]
end

#db=(db) ⇒ Object



77
78
79
# File 'lib/redis/client.rb', line 77

def db=(db)
  @options[:db] = db.to_i
end

#disconnectObject Also known as: close



288
289
290
# File 'lib/redis/client.rb', line 288

def disconnect
  connection.disconnect if connected?
end

#driverObject



81
82
83
# File 'lib/redis/client.rb', line 81

def driver
  @options[:driver]
end

#hostObject



41
42
43
# File 'lib/redis/client.rb', line 41

def host
  @options[:host]
end

#idObject



153
154
155
# File 'lib/redis/client.rb', line 153

def id
  @options[:id] || "redis://#{location}/#{db}"
end

#inherit_socket?Boolean

Returns:

  • (Boolean)


85
86
87
# File 'lib/redis/client.rb', line 85

def inherit_socket?
  @options[:inherit_socket]
end

#ioObject



298
299
300
301
302
303
304
305
306
307
# File 'lib/redis/client.rb', line 298

def io
  yield
rescue TimeoutError => e1
  # Add a message to the exception without destroying the original stack
  e2 = TimeoutError.new("Connection timed out")
  e2.set_backtrace(e1.backtrace)
  raise e2
rescue Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, Errno::EBADF, Errno::EINVAL => e
  raise ConnectionError, "Connection lost (%s)" % [e.class.name.split("::").last]
end

#locationObject



157
158
159
# File 'lib/redis/client.rb', line 157

def location
  path || "#{host}:#{port}"
end

#passwordObject



69
70
71
# File 'lib/redis/client.rb', line 69

def password
  @options[:password]
end

#pathObject



49
50
51
# File 'lib/redis/client.rb', line 49

def path
  @options[:path]
end

#portObject



45
46
47
# File 'lib/redis/client.rb', line 45

def port
  @options[:port]
end

#process(commands) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/redis/client.rb', line 267

def process(commands)
  logging(commands) do
    ensure_connected do
      commands.each do |command|
        if command_map[command.first]
          command = command.dup
          command[0] = command_map[command.first]
        end

        write(command)
      end

      yield if block_given?
    end
  end
end

#readObject



309
310
311
312
313
314
315
# File 'lib/redis/client.rb', line 309

def read
  io do
    value = connection.read
    @pending_reads -= 1
    value
  end
end

#read_timeoutObject



53
54
55
# File 'lib/redis/client.rb', line 53

def read_timeout
  @options[:read_timeout]
end

#reconnectObject



293
294
295
296
# File 'lib/redis/client.rb', line 293

def reconnect
  disconnect
  connect
end

#schemeObject



37
38
39
# File 'lib/redis/client.rb', line 37

def scheme
  @options[:scheme]
end

#timeoutObject



61
62
63
# File 'lib/redis/client.rb', line 61

def timeout
  @options[:read_timeout]
end

#usernameObject



65
66
67
# File 'lib/redis/client.rb', line 65

def username
  @options[:username]
end

#with_reconnect(val = true) ⇒ Object



342
343
344
345
346
347
# File 'lib/redis/client.rb', line 342

def with_reconnect(val = true)
  original, @reconnect = @reconnect, val
  yield
ensure
  @reconnect = original
end

#with_socket_timeout(timeout) ⇒ Object



324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/redis/client.rb', line 324

def with_socket_timeout(timeout)
  connect unless connected?
  original = @options[:read_timeout]

  begin
    connection.timeout = timeout
    @options[:read_timeout] = timeout # for reconnection
    yield
  ensure
    connection.timeout = self.timeout if connected?
    @options[:read_timeout] = original
  end
end

#without_reconnect(&blk) ⇒ Object



349
350
351
# File 'lib/redis/client.rb', line 349

def without_reconnect(&blk)
  with_reconnect(false, &blk)
end

#without_socket_timeout(&blk) ⇒ Object



338
339
340
# File 'lib/redis/client.rb', line 338

def without_socket_timeout(&blk)
  with_socket_timeout(0, &blk)
end

#write(command) ⇒ Object



317
318
319
320
321
322
# File 'lib/redis/client.rb', line 317

def write(command)
  io do
    @pending_reads += 1
    connection.write(command)
  end
end