Class: Redis

Inherits:
Object
  • Object
show all
Includes:
Commands
Defined in:
lib/redis.rb,
lib/redis/client.rb,
lib/redis/errors.rb,
lib/redis/cluster.rb,
lib/redis/version.rb,
lib/redis/commands.rb,
lib/redis/pipeline.rb,
lib/redis/hash_ring.rb,
lib/redis/subscribe.rb,
lib/redis/distributed.rb,
lib/redis/cluster/node.rb,
lib/redis/cluster/slot.rb,
lib/redis/commands/geo.rb,
lib/redis/commands/keys.rb,
lib/redis/commands/sets.rb,
lib/redis/cluster/option.rb,
lib/redis/commands/lists.rb,
lib/redis/cluster/command.rb,
lib/redis/commands/hashes.rb,
lib/redis/commands/pubsub.rb,
lib/redis/commands/server.rb,
lib/redis/connection/ruby.rb,
lib/redis/cluster/node_key.rb,
lib/redis/commands/bitmaps.rb,
lib/redis/commands/cluster.rb,
lib/redis/commands/streams.rb,
lib/redis/commands/strings.rb,
lib/redis/commands/scripting.rb,
lib/redis/connection/hiredis.rb,
lib/redis/cluster/node_loader.rb,
lib/redis/cluster/slot_loader.rb,
lib/redis/commands/connection.rb,
lib/redis/connection/registry.rb,
lib/redis/commands/sorted_sets.rb,
lib/redis/connection/synchrony.rb,
lib/redis/commands/transactions.rb,
lib/redis/cluster/command_loader.rb,
lib/redis/commands/hyper_log_log.rb,
lib/redis/connection/command_helper.rb,
lib/redis/cluster/key_slot_converter.rb

Defined Under Namespace

Modules: Commands, Connection Classes: BaseConnectionError, BaseError, CannotConnectError, Client, Cluster, CommandError, ConnectionError, DeprecatedMulti, DeprecatedPipeline, Distributed, Future, FutureNotReady, HashRing, InheritedError, InvalidClientOptionError, Pipeline, PipelinedConnection, ProtocolError, SubscribedClient, Subscription, TimeoutError

Constant Summary collapse

BASE_PATH =
__dir__
Deprecated =
Class.new(StandardError)
VERSION =
'4.6.0'

Constants included from Commands

Commands::Boolify, Commands::BoolifySet, Commands::Floatify, Commands::FloatifyPairs, Commands::Hashify, Commands::HashifyClusterNodeInfo, Commands::HashifyClusterNodes, Commands::HashifyClusterSlaves, Commands::HashifyClusterSlots, Commands::HashifyInfo, Commands::HashifyStreamAutoclaim, Commands::HashifyStreamAutoclaimJustId, Commands::HashifyStreamEntries, Commands::HashifyStreamPendingDetails, Commands::HashifyStreamPendings, Commands::HashifyStreams, Commands::Noop, Commands::Pairify

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Commands

#call, #sentinel

Methods included from Commands::Transactions

#discard, #exec, #unwatch, #watch

Methods included from Commands::Strings

#append, #decr, #decrby, #get, #getdel, #getex, #getrange, #getset, #incr, #incrby, #incrbyfloat, #mapped_mget, #mapped_mset, #mapped_msetnx, #mget, #mset, #msetnx, #psetex, #set, #setex, #setnx, #setrange, #strlen

Methods included from Commands::Streams

#xack, #xadd, #xautoclaim, #xclaim, #xdel, #xgroup, #xinfo, #xlen, #xpending, #xrange, #xread, #xreadgroup, #xrevrange, #xtrim

Methods included from Commands::SortedSets

#bzpopmax, #bzpopmin, #zadd, #zcard, #zcount, #zdiff, #zdiffstore, #zincrby, #zinter, #zinterstore, #zlexcount, #zmscore, #zpopmax, #zpopmin, #zrandmember, #zrange, #zrangebylex, #zrangebyscore, #zrangestore, #zrank, #zrem, #zremrangebyrank, #zremrangebyscore, #zrevrange, #zrevrangebylex, #zrevrangebyscore, #zrevrank, #zscan, #zscan_each, #zscore, #zunion, #zunionstore

Methods included from Commands::Sets

#sadd, #scard, #sdiff, #sdiffstore, #sinter, #sinterstore, #sismember, #smembers, #smismember, #smove, #spop, #srandmember, #srem, #sscan, #sscan_each, #sunion, #sunionstore

Methods included from Commands::Server

#bgrewriteaof, #bgsave, #client, #config, #dbsize, #debug, #flushall, #flushdb, #info, #lastsave, #monitor, #save, #shutdown, #slaveof, #slowlog, #sync, #time

Methods included from Commands::Scripting

#eval, #evalsha, #script

Methods included from Commands::Pubsub

#psubscribe, #psubscribe_with_timeout, #publish, #pubsub, #punsubscribe, #subscribe, #subscribe_with_timeout, #subscribed?, #unsubscribe

Methods included from Commands::Lists

#blmove, #blpop, #brpop, #brpoplpush, #lindex, #linsert, #llen, #lmove, #lpop, #lpush, #lpushx, #lrange, #lrem, #lset, #ltrim, #rpop, #rpoplpush, #rpush, #rpushx

Methods included from Commands::Keys

#_exists, #copy, #del, #dump, #exists, #exists?, #expire, #expireat, #keys, #migrate, #move, #object, #persist, #pexpire, #pexpireat, #pttl, #randomkey, #rename, #renamenx, #restore, #scan, #scan_each, #sort, #ttl, #type, #unlink

Methods included from Commands::HyperLogLog

#pfadd, #pfcount, #pfmerge

Methods included from Commands::Hashes

#hdel, #hexists, #hget, #hgetall, #hincrby, #hincrbyfloat, #hkeys, #hlen, #hmget, #hmset, #hrandfield, #hscan, #hscan_each, #hset, #hsetnx, #hvals, #mapped_hmget, #mapped_hmset

Methods included from Commands::Geo

#geoadd, #geodist, #geohash, #geopos, #georadius, #georadiusbymember

Methods included from Connection

drivers

Methods included from Commands::Cluster

#asking, #cluster

Methods included from Commands::Bitmaps

#bitcount, #bitop, #bitpos, #getbit, #setbit

Constructor Details

#initialize(options = {}) ⇒ Redis

Create a new client instance

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :url (String) — default: value of the environment variable REDIS_URL

    a Redis URL, for a TCP connection: ‘redis://:@[hostname]:/[db]` (password, port and database are optional), for a unix socket

    connection: `unix://[path to Redis socket]`. This overrides all other options.
    
  • :host (String) — default: "127.0.0.1"

    server hostname

  • :port (Integer) — default: 6379

    server port

  • :path (String)

    path to server socket (overrides host and port)

  • :timeout (Float) — default: 5.0

    timeout in seconds

  • :connect_timeout (Float) — default: same as timeout

    timeout for initial connect in seconds

  • :username (String)

    Username to authenticate against server

  • :password (String)

    Password to authenticate against server

  • :db (Integer) — default: 0

    Database to select after initial connect

  • :driver (Symbol)

    Driver to use, currently supported: ‘:ruby`, `:hiredis`, `:synchrony`

  • :id (String)

    ID for the client connection, assigns name to current connection by sending ‘CLIENT SETNAME`

  • :tcp_keepalive (Hash, Integer)

    Keepalive values, if Integer ‘intvl` and `probe` are calculated based on the value, if Hash `time`, `intvl` and `probes` can be specified as a Integer

  • :reconnect_attempts (Integer)

    Number of attempts trying to connect

  • :inherit_socket (Boolean) — default: false

    Whether to use socket in forked process or not

  • :sentinels (Array)

    List of sentinels to contact

  • :role (Symbol) — default: :master

    Role to fetch via Sentinel, either ‘:master` or `:slave`

  • :cluster (Array<String, Hash{Symbol => String, Integer}>)

    List of cluster nodes to contact

  • :replica (Boolean)

    Whether to use readonly replica nodes in Redis Cluster or not

  • :connector (Class)

    Class of custom connector



80
81
82
83
84
85
86
87
# File 'lib/redis.rb', line 80

def initialize(options = {})
  @options = options.dup
  @cluster_mode = options.key?(:cluster)
  client = @cluster_mode ? Cluster : Client
  @original_client = @client = client.new(options)
  @queue = Hash.new { |h, k| h[k] = [] }
  @monitor = Monitor.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Redis::Commands

Class Attribute Details

.exists_returns_integerObject

Returns the value of attribute exists_returns_integer.



14
15
16
# File 'lib/redis.rb', line 14

def exists_returns_integer
  @exists_returns_integer
end

.raise_deprecationsObject

Returns the value of attribute raise_deprecations.



15
16
17
# File 'lib/redis.rb', line 15

def raise_deprecations
  @raise_deprecations
end

.silence_deprecationsObject

Returns the value of attribute silence_deprecations.



15
16
17
# File 'lib/redis.rb', line 15

def silence_deprecations
  @silence_deprecations
end

Class Method Details

.currentObject



39
40
41
42
# File 'lib/redis.rb', line 39

def current
  deprecate!("`Redis.current=` is deprecated and will be removed in 5.0. (called from: #{caller(1, 1).first})")
  @current ||= Redis.new
end

.current=(redis) ⇒ Object



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

def current=(redis)
  deprecate!("`Redis.current=` is deprecated and will be removed in 5.0. (called from: #{caller(1, 1).first})")
  @current = redis
end

.deprecate!(message) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/redis.rb', line 29

def deprecate!(message)
  unless silence_deprecations
    if raise_deprecations
      raise Deprecated, message
    else
      ::Kernel.warn(message)
    end
  end
end

Instance Method Details

#_clientObject



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

def _client
  @client
end

#closeObject Also known as: disconnect!

Disconnect the client as quickly and silently as possible.



107
108
109
# File 'lib/redis.rb', line 107

def close
  @original_client.disconnect
end

#commitObject

Deprecated.

Sends all commands in the queue.

See redis.io/topics/pipelining for more details.



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/redis.rb', line 133

def commit
  ::Redis.deprecate!(
    "Redis#commit is deprecated and will be removed in Redis 5.0.0. Use Redis#pipelined instead. " \
    "(called from: #{Kernel.caller(1, 1).first})"
  )

  synchronize do |client|
    begin
      pipeline = Pipeline.new(client)
      @queue[Thread.current.object_id].each do |command|
        pipeline.call(command)
      end

      client.call_pipelined(pipeline)
    ensure
      @queue.delete(Thread.current.object_id)
    end
  end
end

#connected?Boolean

Test whether or not the client is connected

Returns:

  • (Boolean)


102
103
104
# File 'lib/redis.rb', line 102

def connected?
  @original_client.connected?
end

#connectionObject



243
244
245
246
247
248
249
250
251
252
253
# File 'lib/redis.rb', line 243

def connection
  return @original_client.connection_info if @cluster_mode

  {
    host: @original_client.host,
    port: @original_client.port,
    db: @original_client.db,
    id: @original_client.id,
    location: @original_client.location
  }
end

#dupObject



239
240
241
# File 'lib/redis.rb', line 239

def dup
  self.class.new(@options)
end

#idObject



231
232
233
# File 'lib/redis.rb', line 231

def id
  @original_client.id
end

#inspectObject



235
236
237
# File 'lib/redis.rb', line 235

def inspect
  "#<Redis client v#{Redis::VERSION} for #{id}>"
end

#multi {|multi| ... } ⇒ String, Array<...>

Mark the start of a transaction block.

Passing a block is optional.

Examples:

With a block

redis.multi do |multi|
  multi.set("key", "value")
  multi.incr("counter")
end # => ["OK", 6]

Without a block

redis.multi
  # => "OK"
redis.set("key", "value")
  # => "QUEUED"
redis.incr("counter")
  # => "QUEUED"
redis.exec
  # => ["OK", 6]

Yields:

  • (multi)

    the commands that are called inside this block are cached and written to the server upon returning from it

Yield Parameters:

  • multi (Redis)

    ‘self`

Returns:

  • (String, Array<...>)
    • when a block is not given, ‘OK`

    • when a block is given, an array with replies

See Also:



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/redis.rb', line 207

def multi(&block)
  if block_given?
    deprecation_displayed = false
    if block&.arity == 0
      Pipeline.deprecation_warning("multi", Kernel.caller_locations(1, 5))
      deprecation_displayed = true
    end

    synchronize do |prior_client|
      begin
        pipeline = Pipeline::Multi.new(prior_client)
        @client = deprecation_displayed ? pipeline : DeprecatedMulti.new(pipeline)
        pipelined_connection = PipelinedConnection.new(pipeline)
        yield pipelined_connection
        prior_client.call_pipeline(pipeline)
      ensure
        @client = prior_client
      end
    end
  else
    send_command([:multi])
  end
end

#pipelined(&block) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/redis.rb', line 157

def pipelined(&block)
  deprecation_displayed = false
  if block&.arity == 0
    Pipeline.deprecation_warning("pipelined", Kernel.caller_locations(1, 5))
    deprecation_displayed = true
  end

  synchronize do |prior_client|
    begin
      pipeline = Pipeline.new(prior_client)
      @client = deprecation_displayed ? pipeline : DeprecatedPipeline.new(pipeline)
      pipelined_connection = PipelinedConnection.new(pipeline)
      yield pipelined_connection
      prior_client.call_pipeline(pipeline)
    ensure
      @client = prior_client
    end
  end
end

#queue(*command) ⇒ Object

Deprecated.

Queues a command for pipelining.

Commands in the queue are executed with the Redis#commit method.

See redis.io/topics/pipelining for more details.



118
119
120
121
122
123
124
125
126
127
# File 'lib/redis.rb', line 118

def queue(*command)
  ::Redis.deprecate!(
    "Redis#queue is deprecated and will be removed in Redis 5.0.0. Use Redis#pipelined instead." \
    "(called from: #{caller(1, 1).first})"
  )

  synchronize do
    @queue[Thread.current.object_id] << command
  end
end

#with_reconnect(val = true, &blk) ⇒ Object

Run code with the client reconnecting



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

def with_reconnect(val = true, &blk)
  synchronize do |client|
    client.with_reconnect(val, &blk)
  end
end

#without_reconnect(&blk) ⇒ Object

Run code without the client reconnecting



97
98
99
# File 'lib/redis.rb', line 97

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