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/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/cluster/node_loader.rb,
lib/redis/cluster/slot_loader.rb,
lib/redis/commands/connection.rb,
lib/redis/commands/sorted_sets.rb,
lib/redis/commands/transactions.rb,
lib/redis/cluster/command_loader.rb,
lib/redis/commands/hyper_log_log.rb,
lib/redis/cluster/key_slot_converter.rb

Defined Under Namespace

Modules: Commands Classes: BaseConnectionError, BaseError, CannotConnectError, Client, Cluster, CommandError, ConnectionError, DeprecatedMulti, DeprecatedPipeline, Distributed, Future, FutureNotReady, HashRing, InheritedError, InvalidClientOptionError, MultiFuture, 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 Commands::Connection

#auth, #echo, #ping, #quit, #select

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://:[password]@[hostname]:[port]/[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

  • :fixed_hostname (String)

    Specify a FQDN if cluster mode enabled and client has to connect nodes via single endpoint with SSL/TLS

  • :connector (Class)

    Class of custom connector


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

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


159
160
161
# File 'lib/redis.rb', line 159

def _client
  @client
end

#closeObject Also known as: disconnect!

Disconnect the client as quickly and silently as possible.


109
110
111
# File 'lib/redis.rb', line 109

def close
  @original_client.disconnect
end

#commitObject

Deprecated.

Sends all commands in the queue.

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


139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/redis.rb', line 139

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)

104
105
106
# File 'lib/redis.rb', line 104

def connected?
  @original_client.connected?
end

#connectionObject


249
250
251
252
253
254
255
256
257
258
259
# File 'lib/redis.rb', line 249

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


245
246
247
# File 'lib/redis.rb', line 245

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

#idObject


237
238
239
# File 'lib/redis.rb', line 237

def id
  @original_client.id
end

#inspectObject


241
242
243
# File 'lib/redis.rb', line 241

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:

Returns:

  • (String, Array<...>)
    • when a block is not given, OK
    • when a block is given, an array with replies

See Also:


213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/redis.rb', line 213

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


163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/redis.rb', line 163

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 http://redis.io/topics/pipelining for more details.


124
125
126
127
128
129
130
131
132
133
# File 'lib/redis.rb', line 124

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 {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (Redis)

    the object that the method was called on


114
115
116
# File 'lib/redis.rb', line 114

def with
  yield self
end

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

Run code with the client reconnecting


92
93
94
95
96
# File 'lib/redis.rb', line 92

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


99
100
101
# File 'lib/redis.rb', line 99

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