123456789_123456789_123456789_123456789_123456789_

Class: Redis

Relationships & Source Files
Namespace Children
Modules:
Classes:
Exceptions:
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
Inherits: Object
Defined in: lib/redis.rb,
lib/redis/client.rb,
lib/redis/commands.rb,
lib/redis/distributed.rb,
lib/redis/errors.rb,
lib/redis/hash_ring.rb,
lib/redis/pipeline.rb,
lib/redis/subscribe.rb,
lib/redis/version.rb,
lib/redis/commands/bitmaps.rb,
lib/redis/commands/cluster.rb,
lib/redis/commands/connection.rb,
lib/redis/commands/geo.rb,
lib/redis/commands/hashes.rb,
lib/redis/commands/hyper_log_log.rb,
lib/redis/commands/keys.rb,
lib/redis/commands/lists.rb,
lib/redis/commands/pubsub.rb,
lib/redis/commands/scripting.rb,
lib/redis/commands/server.rb,
lib/redis/commands/sets.rb,
lib/redis/commands/sorted_sets.rb,
lib/redis/commands/streams.rb,
lib/redis/commands/strings.rb,
lib/redis/commands/transactions.rb

Constant Summary

Commands - Included

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

Class Attribute Summary

Class Method Summary

Instance Attribute Summary

::Redis::Commands::Pubsub - Included

Instance Method Summary

Commands - Included

#call

Sends a command to Redis and returns its reply.

#sentinel

Interact with the sentinel command (masters, master, slaves, failover).

#method_missing

::Redis::Commands::Transactions - Included

#discard

Discard all commands issued after MULTI.

#exec

Execute all commands issued after MULTI.

#multi

Mark the start of a transaction block.

#unwatch

Forget about all watched keys.

#watch

Watch the given keys to determine execution of the MULTI/EXEC block.

::Redis::Commands::Strings - Included

#append

Append a value to a key.

#decr

Decrement the integer value of a key by one.

#decrby

Decrement the integer value of a key by the given number.

#get

Get the value of a key.

#getdel

Get the value of key and delete the key.

#getex

Get the value of key and optionally set its expiration.

#getrange

Get a substring of the string stored at a key.

#getset

Set the string value of a key and return its old value.

#incr

Increment the integer value of a key by one.

#incrby

Increment the integer value of a key by the given integer number.

#incrbyfloat

Increment the numeric value of a key by the given float number.

#mapped_mget

Get the values of all the given keys.

#mapped_mset

Set one or more values.

#mapped_msetnx

Set one or more values, only if none of the keys exist.

#mget

Get the values of all the given keys.

#mset

Set one or more values.

#msetnx

Set one or more values, only if none of the keys exist.

#psetex

Set the time to live in milliseconds of a key.

#set

Set the string value of a key.

#setex

Set the time to live in seconds of a key.

#setnx

Set the value of a key, only if the key does not exist.

#setrange

Overwrite part of a string at key starting at the specified offset.

#strlen

Get the length of the value stored in a key.

::Redis::Commands::Streams - Included

#xack

Removes one or multiple entries from the pending entries list of a stream consumer group.

#xadd

Add new entry to the stream.

#xautoclaim

Transfers ownership of pending stream entries that match the specified criteria.

#xclaim

Changes the ownership of a pending entry.

#xdel

Delete entries by entry ids.

#xgroup

Manages the consumer group of the stream.

#xinfo

Returns the stream information each subcommand.

#xlen

Returns the number of entries inside a stream.

#xpending

Fetches not acknowledging pending entries.

#xrange

Fetches entries of the stream in ascending order.

#xread

Fetches entries from one or multiple streams.

#xreadgroup

Fetches a subset of the entries from one or multiple streams related with the consumer group.

#xrevrange

Fetches entries of the stream in descending order.

#xtrim

Trims older entries of the stream if needed.

#_xread

::Redis::Commands::SortedSets - Included

#bzmpop

Removes and returns up to count members with scores in the sorted set stored at key.

#bzpopmax

Removes and returns up to count members with the highest scores in the sorted set stored at keys,.

#bzpopmin

Removes and returns up to count members with the lowest scores in the sorted set stored at keys,.

#zadd

Add one or more members to a sorted set, or update the score for members that already exist.

#zcard

Get the number of members in a sorted set.

#zcount

Count the members in a sorted set with scores within the given values.

#zdiff

Return the difference between the first and all successive input sorted sets.

#zdiffstore

Compute the difference between the first and all successive input sorted sets and store the resulting sorted set in a new key.

#zincrby

Increment the score of a member in a sorted set.

#zinter

Return the intersection of multiple sorted sets.

#zinterstore

Intersect multiple sorted sets and store the resulting sorted set in a new key.

#zlexcount

Count the members, with the same score in a sorted set, within the given lexicographical range.

#zmpop

Removes and returns up to count members with scores in the sorted set stored at key.

#zmscore

Get the scores associated with the given members in a sorted set.

#zpopmax

Removes and returns up to count members with the highest scores in the sorted set stored at key.

#zpopmin

Removes and returns up to count members with the lowest scores in the sorted set stored at key.

#zrandmember

Get one or more random members from a sorted set.

#zrange

Return a range of members in a sorted set, by index, score or lexicographical ordering.

#zrangebylex

Return a range of members with the same score in a sorted set, by lexicographical ordering.

#zrangebyscore

Return a range of members in a sorted set, by score.

#zrangestore

Select a range of members in a sorted set, by index, score or lexicographical ordering and store the resulting sorted set in a new key.

#zrank

Determine the index of a member in a sorted set.

#zrem

Remove one or more members from a sorted set.

#zremrangebyrank

Remove all members in a sorted set within the given indexes.

#zremrangebyscore

Remove all members in a sorted set within the given scores.

#zrevrange

Return a range of members in a sorted set, by index, with scores ordered from high to low.

#zrevrangebylex

Return a range of members with the same score in a sorted set, by reversed lexicographical ordering.

#zrevrangebyscore

Return a range of members in a sorted set, by score, with scores ordered from high to low.

#zrevrank

Determine the index of a member in a sorted set, with scores ordered from high to low.

#zscan

Scan a sorted set.

#zscan_each

Scan a sorted set.

#zscore

Get the score associated with the given member in a sorted set.

#zunion

Return the union of multiple sorted sets.

#zunionstore

Add multiple sorted sets and store the resulting sorted set in a new key.

#_zsets_operation, #_zsets_operation_store

::Redis::Commands::Sets - Included

#sadd

Add one or more members to a set.

#sadd?

Add one or more members to a set.

#scard

Get the number of members in a set.

#sdiff

Subtract multiple sets.

#sdiffstore

Subtract multiple sets and store the resulting set in a key.

#sinter

Intersect multiple sets.

#sinterstore

Intersect multiple sets and store the resulting set in a key.

#sismember

Determine if a given value is a member of a set.

#smembers

Get all the members in a set.

#smismember

Determine if multiple values are members of a set.

#smove

Move a member from one set to another.

#spop

Remove and return one or more random member from a set.

#srandmember

Get one or more random members from a set.

#srem

Remove one or more members from a set.

#srem?

Remove one or more members from a set.

#sscan

Scan a set.

#sscan_each

Scan a set.

#sunion

Add multiple sets.

#sunionstore

Add multiple sets and store the resulting set in a key.

::Redis::Commands::Server - Included

#bgrewriteaof

Asynchronously rewrite the append-only file.

#bgsave

Asynchronously save the dataset to disk.

#client

Manage client connections.

#config

Get or set server configuration parameters.

#dbsize

Return the number of keys in the selected database.

#debug,
#flushall

Remove all keys from all databases.

#flushdb

Remove all keys from the current database.

#info

Get information and statistics about the server.

#lastsave

Get the UNIX time stamp of the last successful save to disk.

#monitor

Listen for all requests received by the server in real time.

#save

Synchronously save the dataset to disk.

#shutdown

Synchronously save the dataset to disk and then shut down the server.

#slaveof

Make the server a slave of another instance, or promote it as master.

#slowlog

Interact with the slowlog (get, len, reset).

#sync

Internal command used for replication.

#time

Return the server time.

::Redis::Commands::Scripting - Included

#eval

Evaluate Lua script.

#evalsha

Evaluate Lua script by its SHA.

#script

Control remote script registry.

#_eval

::Redis::Commands::Pubsub - Included

#psubscribe

Listen for messages published to channels matching the given patterns.

#psubscribe_with_timeout

Listen for messages published to channels matching the given patterns.

#publish

Post a message to a channel.

#pubsub

Inspect the state of the Pub/Sub subsystem.

#punsubscribe

Stop listening for messages posted to channels matching the given patterns.

#spublish

Post a message to a channel in a shard.

#ssubscribe

Listen for messages published to the given channels in a shard.

#ssubscribe_with_timeout

Listen for messages published to the given channels in a shard.

#subscribe

Listen for messages published to the given channels.

#subscribe_with_timeout

Listen for messages published to the given channels.

#sunsubscribe

Stop listening for messages posted to the given channels in a shard.

#unsubscribe

Stop listening for messages posted to the given channels.

::Redis::Commands::Lists - Included

#blmove

Remove the first/last element in a list and append/prepend it to another list and return it, or block until one is available.

#blmpop

Pops one or more elements from the first non-empty list key from the list of provided key names.

#blpop

Remove and get the first element in a list, or block until one is available.

#brpop

Remove and get the last element in a list, or block until one is available.

#brpoplpush

Pop a value from a list, push it to another list and return it; or block until one is available.

#lindex

Get an element from a list by its index.

#linsert

Insert an element before or after another element in a list.

#llen

Get the length of a list.

#lmove

Remove the first/last element in a list, append/prepend it to another list and return it.

#lmpop

Pops one or more elements from the first non-empty list key from the list of provided key names.

#lpop

Remove and get the first elements in a list.

#lpush

Prepend one or more values to a list, creating the list if it doesn't exist.

#lpushx

Prepend a value to a list, only if the list exists.

#lrange

Get a range of elements from a list.

#lrem

Remove elements from a list.

#lset

Set the value of an element in a list by its index.

#ltrim

Trim a list to the specified range.

#rpop

Remove and get the last elements in a list.

#rpoplpush

Remove the last element in a list, append it to another list and return it.

#rpush

Append one or more values to a list, creating the list if it doesn't exist.

#rpushx

Append a value to a list, only if the list exists.

#_bpop, #_normalize_move_wheres

::Redis::Commands::Keys - Included

#copy

Copy a value from one key to another.

#del

Delete one or more keys.

#dump

Return a serialized version of the value stored at a key.

#exists

Determine how many of the keys exists.

#exists?

Determine if any of the keys exists.

#expire

Set a key's time to live in seconds.

#expireat

Set the expiration for a key as a UNIX timestamp.

#expiretime

Get a key's expiry time specified as number of seconds from UNIX Epoch.

#keys

Find all keys matching the given pattern.

#migrate

Transfer a key from the connected instance to another instance.

#move

Move a key to another database.

#object,
#persist

Remove the expiration from a key.

#pexpire

Set a key's time to live in milliseconds.

#pexpireat

Set the expiration for a key as number of milliseconds from UNIX Epoch.

#pexpiretime

Get a key's expiry time specified as number of milliseconds from UNIX Epoch.

#pttl

Get the time to live (in milliseconds) for a key.

#randomkey

Return a random key from the keyspace.

#rename

Rename a key.

#renamenx

Rename a key, only if the new key does not exist.

#restore

Create a key using the serialized value, previously obtained using DUMP.

#scan

Scan the keyspace.

#scan_each

Scan the keyspace.

#sort

Sort the elements in a list, set or sorted set.

#ttl

Get the time to live (in seconds) for a key.

#type

Determine the type stored at key.

#unlink

Unlink one or more keys.

#_scan

::Redis::Commands::HyperLogLog - Included

#pfadd

Add one or more members to a HyperLogLog structure.

#pfcount

Get the approximate cardinality of members added to HyperLogLog structure.

#pfmerge

Merge multiple HyperLogLog values into an unique value that will approximate the cardinality of the union of the observed Sets of the source HyperLogLog structures.

::Redis::Commands::Hashes - Included

#hdel

Delete one or more hash fields.

#hexists

Determine if a hash field exists.

#hget

Get the value of a hash field.

#hgetall

Get all the fields and values in a hash.

#hincrby

Increment the integer value of a hash field by the given integer number.

#hincrbyfloat

Increment the numeric value of a hash field by the given float number.

#hkeys

Get all the fields in a hash.

#hlen

Get the number of fields in a hash.

#hmget

Get the values of all the given hash fields.

#hmset

Set one or more hash values.

#hrandfield

Get one or more random fields from a hash.

#hscan

Scan a hash.

#hscan_each

Scan a hash.

#hset

Set one or more hash values.

#hsetnx

Set the value of a hash field, only if the field does not exist.

#hvals

Get all the values in a hash.

#mapped_hmget

Get the values of all the given hash fields.

#mapped_hmset

Set one or more hash values.

::Redis::Commands::Geo - Included

#geoadd

Adds the specified geospatial items (latitude, longitude, name) to the specified key.

#geodist

Returns the distance between two members of a geospatial index.

#geohash

Returns geohash string representing position for specified members of the specified key.

#geopos

Returns longitude and latitude of members of a geospatial index.

#georadius

Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point.

#georadiusbymember

Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from an already existing member.

#_geoarguments

::Redis::Commands::Cluster - Included

#asking

Sends ASKING command to random node and returns its reply.

#cluster

Sends CLUSTER * command to random node and returns its reply.

::Redis::Commands::Bitmaps - Included

#bitcount

Count the number of set bits in a range of the string value stored at key.

#bitop

Perform a bitwise operation between strings and store the resulting string in a key.

#bitpos

Return the position of the first bit set to 1 or 0 in a string.

#getbit

Returns the bit value at offset in the string value stored at key.

#setbit

Sets or clears the bit at offset in the string value stored at key.

Constructor Details

.new(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: 1.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 connect and on reconnects

  • :driver (Symbol)

    Driver to use, currently supported: :ruby, :hiredis

  • :id (String)

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

  • :reconnect_attempts (Integer, Array<Integer, Float>)

    Number of attempts trying to connect, or a list of sleep duration between attempts.

  • :inherit_socket (Boolean) — default: false

    Whether to use socket in forked process or not

  • :name (String)

    The name of the server group to connect to.

  • :sentinels (Array)

    List of sentinels to contact

[ GitHub ]

  
# File 'lib/redis.rb', line 63

def initialize(options = {})
  @monitor = Monitor.new
  @options = options.dup
  @options[:reconnect_attempts] = 1 unless @options.key?(:reconnect_attempts)
  if ENV["REDIS_URL"] && SERVER_URL_OPTIONS.none? { |o| @options.key?(o) }
    @options[:url] = ENV["REDIS_URL"]
  end
  inherit_socket = @options.delete(:inherit_socket)
  @subscription_client = nil

  @client = initialize_client(@options)
  @client.inherit_socket! if inherit_socket
end

Dynamic Method Handling

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

Class Attribute Details

.raise_deprecations (rw)

[ GitHub ]

  
# File 'lib/redis.rb', line 12

attr_accessor :silence_deprecations, :raise_deprecations

.silence_deprecations (rw)

[ GitHub ]

  
# File 'lib/redis.rb', line 12

attr_accessor :silence_deprecations, :raise_deprecations

Class Method Details

.deprecate!(message)

[ GitHub ]

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

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

Instance Attribute Details

#connected?Boolean (readonly)

Test whether or not the client is connected

[ GitHub ]

  
# File 'lib/redis.rb', line 83

def connected?
  @client.connected? || @subscription_client&.connected?
end

Instance Method Details

#_client

[ GitHub ]

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

def _client
  @client
end

#_subscription(method, timeout, channels, block) (private)

[ GitHub ]

  
# File 'lib/redis.rb', line 164

def _subscription(method, timeout, channels, block)
  if block
    if @subscription_client
      raise SubscriptionError, "This client is already subscribed"
    end

    begin
      @subscription_client = SubscribedClient.new(@client.pubsub)
      if timeout > 0
        @subscription_client.send(method, timeout, *channels, &block)
      else
        @subscription_client.send(method, *channels, &block)
      end
    ensure
      @subscription_client&.close
      @subscription_client = nil
    end
  else
    unless @subscription_client
      raise SubscriptionError, "This client is not subscribed"
    end

    @subscription_client.call_v([method].concat(channels))
  end
end

#close Also known as: #disconnect!

Disconnect the client as quickly and silently as possible.

[ GitHub ]

  
# File 'lib/redis.rb', line 88

def close
  @client.close
  @subscription_client&.close
end

#connection

[ GitHub ]

  
# File 'lib/redis.rb', line 122

def connection
  {
    host: @client.host,
    port: @client.port,
    db: @client.db,
    id: id,
    location: "#{@client.host}:#{@client.port}"
  }
end

#disconnect!

Alias for #close.

[ GitHub ]

  
# File 'lib/redis.rb', line 92

alias disconnect! close

#dup

[ GitHub ]

  
# File 'lib/redis.rb', line 118

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

#id

[ GitHub ]

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

def id
  @client.id || @client.server_url
end

#initialize_client(options) (private)

[ GitHub ]

  
# File 'lib/redis.rb', line 134

def initialize_client(options)
  if options.key?(:cluster)
    raise "Redis Cluster support was moved to the `redis-clustering` gem."
  end

  if options.key?(:sentinels)
    Client.sentinel(**options).new_client
  else
    Client.config(**options).new_client
  end
end

#inspect

[ GitHub ]

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

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

#pipelined(exception: true)

[ GitHub ]

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

def pipelined(exception: true)
  synchronize do |client|
    client.pipelined(exception: exception) do |raw_pipeline|
      yield PipelinedConnection.new(raw_pipeline, exception: exception)
    end
  end
end

#send_blocking_command(command, timeout, &block) (private)

[ GitHub ]

  
# File 'lib/redis.rb', line 158

def send_blocking_command(command, timeout, &block)
  @monitor.synchronize do
    @client.blocking_call_v(timeout, command, &block)
  end
end

#send_command(command, &block) (private)

[ GitHub ]

  
# File 'lib/redis.rb', line 150

def send_command(command, &block)
  @monitor.synchronize do
    @client.call_v(command, &block)
  end
rescue ::RedisClient::Error => error
  Client.translate_error!(error)
end

#synchronize (private)

[ GitHub ]

  
# File 'lib/redis.rb', line 146

def synchronize
  @monitor.synchronize { yield(@client) }
end

#with {|_self| ... }

Yields:

  • (_self)

Yield Parameters:

  • _self (Redis)

    the object that the method was called on

[ GitHub ]

  
# File 'lib/redis.rb', line 94

def with
  yield self
end

#without_reconnect(&block)

Run code without the client reconnecting

[ GitHub ]

  
# File 'lib/redis.rb', line 78

def without_reconnect(&block)
  @client.disable_reconnection(&block)
end