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/lib_identity.rb,
lib/redis/pipeline.rb,
lib/redis/subscribe.rb,
lib/redis/version.rb,
lib/redis/commands/arrays.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,
lib/redis/commands/modules/json.rb,
lib/redis/commands/modules/search.rb,
lib/redis/commands/modules/search/aggregation.rb,
lib/redis/commands/modules/search/dialect.rb,
lib/redis/commands/modules/search/field.rb,
lib/redis/commands/modules/search/hybrid.rb,
lib/redis/commands/modules/search/index.rb,
lib/redis/commands/modules/search/index_definition.rb,
lib/redis/commands/modules/search/miscellaneous.rb,
lib/redis/commands/modules/search/query.rb,
lib/redis/commands/modules/search/result.rb,
lib/redis/commands/modules/search/schema.rb

Constant Summary

::Redis::Commands::Json - Included

JSON_SET_FPHA_TYPES, NumincrbyNormalize, TypeNormalize

::Redis::Commands::Search - Included

DEFAULT_DIALECT

Commands - Included

Boolify, BoolifySet, EMPTY_STREAM_RESPONSE, Floatify, FloatifyPair, FloatifyPairs, Hashify, HashifyArrayInfo, 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.

#increx

Increment the numeric value of a key atomically, with optional bounds and expiration control.

#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.

#increx_bound

INCREX bounds decide whether the increment is applied at all, so a Float bound in integer mode must raise rather than silently truncate (Integer(2.9) => 2) — mirroring how by: selects the mode strictly.

::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.

#xnack

Releases pending entries back to the consumer group's Pending Entries List without acknowledging them.

#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.

#sdiffcard

Get the number of members in the difference between the first set and all successive 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.

#sunioncard

Get the number of distinct members in the union of 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::Search - Included

#create_index

Create an index and return a high-level Search::Index bound to this client.

#ft_aggregate

Run an aggregation pipeline, or read the next batch of a cursor.

#ft_aliasadd

Add an alias for an index.

#ft_aliasdel

Remove an index alias.

#ft_aliaslist

List all aliases associated with an index (Redis 8.10+).

#ft_aliasupdate

Repoint an existing alias to a different index (or create it if absent).

#ft_alter

Add a field to an existing index's schema (+FT.ALTER ...

#ft_config_get

Get a runtime Query Engine configuration option.

#ft_config_set

Set a runtime Query Engine configuration option.

#ft_create

Create a search index over HASH or JSON keys.

#ft_cursor_del

Discard an aggregation cursor.

#ft_cursor_read

Read the next batch of results from an aggregation cursor.

#ft_dictadd

Add terms to a custom dictionary.

#ft_dictdel

Remove terms from a custom dictionary.

#ft_dictdump

Dump all terms in a custom dictionary.

#ft_dropindex

Drop an index.

#ft_explain

Return the execution plan for a query without running it.

#ft_hybrid_search

Run a hybrid (lexical + vector) search.

#ft_info

Return information and statistics about an index.

#ft_profile

Profile the execution of a SEARCH or AGGREGATE query (timing/heuristics).

#ft_search

Search an index.

#ft_spellcheck

Perform spelling correction over a query against an index.

#ft_sugadd

Add a suggestion string to an auto-complete dictionary.

#ft_sugdel

Delete a string from a suggestion dictionary.

#ft_sugget

Get auto-complete suggestions for a prefix.

#ft_suglen

Get the number of entries in a suggestion dictionary.

#ft_syndump

Dump the synonym groups of an index.

#ft_synupdate

Add or update a synonym group on an index.

#ft_tagvals

List the distinct values of a TAG field.

::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::Json - Included

#json_arrappend

Append one or more values to the array at path in the document stored under key.

#json_arrindex

Return the index of the first occurrence of a scalar value in the array at path.

#json_arrinsert

Insert one or more values into the array at path before index (existing elements at and after index shift right; 0 prepends, negative counts from the end).

#json_arrlen

Return the length of the array at path.

#json_arrpop

Remove and return an element from the array at path.

#json_arrtrim

Trim the array at path so it keeps only the inclusive range of elements from start to stop (negative indices count from the end).

#json_clear

Clear the container and numeric value(s) at path: arrays and objects are emptied and numbers are set to 0.

#json_debug_memory

Report the size in bytes of the JSON value(s) at path (the JSON.DEBUG MEMORY subcommand).

#json_del

Delete the value(s) at path in the document stored under key.

#json_forget

Delete the value(s) at path in the document stored under key.

#json_get

Get the JSON value(s) at one or more paths in the document stored under key.

#json_merge

Merge value into the document stored under key at path, following RFC 7396 (JSON Merge Patch): a null value deletes a key, a non-null value creates or updates it, and any value merged into an existing array replaces the whole array.

#json_mget

Get the values at a single path from one or more keys.

#json_mset

Set one or more JSON values atomically, one per key+/+path+/+value triplet.

#json_numincrby

Increment the numeric value(s) at path in the document stored under key by number.

#json_objkeys

Return the key names of the JSON object(s) at path.

#json_objlen

Return the number of keys in the JSON object(s) at path.

#json_set

Set the JSON value at path in the document stored under key.

#json_strappend

Append value to the JSON string(s) at path in the document stored under key.

#json_strlen

Return the length of the JSON string(s) at path.

#json_toggle

Toggle the boolean value(s) at path in the document stored under key.

#json_type

Return the type name of the value(s) at path (e.g. "integer", "string", "object").

#json_path?

RedisJSON distinguishes JSONPath expressions (which start with "$") from legacy paths.

::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.

#blmovem

Remove multiple elements from the head/tail of a list, append/prepend them to another list and return them; or block until the request can be satisfied or the timeout expires.

#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.

#lmovem

Remove multiple elements from the head/tail of a list, append/prepend them to another list and return them.

#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, #_movem_amount_args, #_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.

#hexpire

Sets the time to live in seconds for one or more fields.

#hexpireat

Sets the expiration for one or more fields as an absolute Unix timestamp in seconds.

#hexpiretime

Returns the expiration time of one or more fields as an absolute Unix timestamp in seconds.

#hget

Get the value of a hash field.

#hgetall

Get all the fields and values in a hash.

#himport_discard

Remove fieldset_name from this connection's session.

#himport_discard_all

Remove all fieldsets from this connection's session.

#himport_prepare

Register an ordered list of hash field names under fieldset_name for use by subsequent #himport_set calls on the same connection.

#himport_set

Create or fully replace the hash at key using the field list registered under fieldset_name on this connection.

#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.

#hpersist

Removes the expiration from one or more fields, making them persistent.

#hpexpire

Sets the time to live in milliseconds for one or more fields.

#hpexpireat

Sets the expiration for one or more fields as an absolute Unix timestamp in milliseconds.

#hpexpiretime

Returns the expiration time of one or more fields as an absolute Unix timestamp in milliseconds.

#hpttl

Returns the time to live in milliseconds for one or more fields.

#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.

#httl

Returns the time to live in seconds for one or more fields.

#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.

#hash_field_expiration_condition

The HEXPIRE command family accepts a single optional condition token ([NX | XX | GT | LT]); the server rejects combinations, so fail fast in Ruby.

::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.

#geosearch

Return the members of a geospatial sorted set that are within the borders of the area specified by a given shape, either a circle (BYRADIUS) or a rectangle (BYBOX), starting from a center point given either by member (FROMMEMBER) or by longitude and latitude (FROMLONLAT).

#geosearchstore

Like GEOSEARCH, but stores the result in a destination key.

#_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.

::Redis::Commands::Arrays - Included

#arcount

Get the number of non-empty elements in an array.

#ardel

Delete elements at the specified indices in an array.

#ardelrange

Delete elements in one or more inclusive index ranges.

#arget

Get the value at an index in an array.

#argetrange

Get values in a range of indices.

#argrep

Search array elements within an inclusive index range using one or more textual predicates.

#arinfo

Get metadata about an array.

#arinsert

Insert one or more values at consecutive indices, beginning at the array's insert cursor.

#arlastitems

Get the most recently inserted elements.

#arlen

Get the length of an array (max index + 1).

#armget

Get values at multiple indices in an array.

#armset

Set multiple index-value pairs in an array.

#arnext

Get the next index #arinsert would use.

#arop

Perform an aggregate operation on the non-empty elements in a range.

#arring

Insert one or more values into an array used as a fixed-size ring buffer.

#arscan

Iterate existing elements in an index range.

#arseek

Set the insert cursor of an array to a specific index.

#arset

Set one or more contiguous values starting at an index in an array.

#argrep_bound

ARGREP accepts "-" / "+" as full-range bounds — unlike the other AR* range commands, which take numeric indices only (verified on Redis 8.8).

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

  • :protocol (Integer) — default: 3

    RESP protocol version to negotiate (HELLO). Defaults to RESP3; set to 2 for RESP2. Servers without RESP3 support automatically fall back to RESP2.

  • :id (String)

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

  • :driver_info (String, Array<String>, false)

    Identity a library built on top of redis-rb reports to the server via CLIENT SETINFO, shown as lib-name=redis-rb(<driver_info>) in CLIENT LIST. The recommended format is <name>_v<version>; an Array is joined with ;. Pass false to disable client identification entirely.

  • :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

  • :himport_auto_prepare (Boolean) — default: true

    Whether to automatically re-prepare a HIMPORT fieldset and retry the #himport_set once when the server reports the fieldset was lost (reconnect, failover, RESET). When false, the error is raised to the caller, who is responsible for retaining the schema and calling #himport_prepare again. See the README "Bulk hash ingestion (HIMPORT)" section.

  • :name (String)

    The name of the server group to connect to.

  • :sentinels (Array)

    List of sentinels to contact

[ GitHub ]

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

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
  # Kept as state, not just a local: the RESP3->RESP2 fallback rebuilds @client and must re-apply
  # socket inheritance, otherwise fork safety would be silently lost after a downgrade.
  @inherit_socket = @options.delete(:inherit_socket)
  # HIMPORT fieldsets are server session state that dies with the physical connection; the
  # registry remembers each prepared schema so a lost session can be repaired (see the
  # himport_* overrides below). Deleted from @options so it never reaches RedisClient::Config.
  @himport_auto_prepare = @options.delete(:himport_auto_prepare) != false
  @himport_fieldsets = {}
  @subscription_client = nil

  @client = build_client
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 14

attr_accessor :silence_deprecations, :raise_deprecations

.silence_deprecations (rw)

[ GitHub ]

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

attr_accessor :silence_deprecations, :raise_deprecations

Class Method Details

.deprecate!(message)

[ GitHub ]

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

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 109

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

Instance Method Details

#_client

[ GitHub ]

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

def _client
  @client
end

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

[ GitHub ]

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

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

    begin
      # The pub/sub second socket is opened via @client.pubsub, which connects through
      # ensure_connected rather than a command path. Route it through #synchronize so the same
      # RESP3->RESP2 fallback applies when subscribe is the first operation against an old server.
      @subscription_client = SubscribedClient.new(synchronize(&: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

#build_client (private)

Builds @client from @options and applies any instance-level settings (socket inheritance) that live outside @options. Used both at construction and when the RESP3->RESP2 fallback rebuilds the client, so those settings survive a protocol downgrade.

[ GitHub ]

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

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

#close Also known as: #disconnect!

Disconnect the client as quickly and silently as possible.

[ GitHub ]

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

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

#connection

[ GitHub ]

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

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 118

alias disconnect! close

#dup

[ GitHub ]

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

def dup
  # inherit_socket and himport_auto_prepare are stripped from @options before the client config
  # is built (RedisClient::Config doesn't know them); merge the live values back so the
  # duplicate keeps the caller's settings instead of silently reverting to defaults.
  self.class.new(@options.merge(inherit_socket: @inherit_socket, himport_auto_prepare: @himport_auto_prepare))
end

#himport_discard(fieldset_name)

[ GitHub ]

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

def himport_discard(fieldset_name)
  @monitor.synchronize do
    reply = super
    @himport_fieldsets.delete(fieldset_name.to_s)
    reply
  end
end

#himport_discard_all

[ GitHub ]

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

def himport_discard_all
  @monitor.synchronize do
    reply = super
    @himport_fieldsets.clear
    reply
  end
end

#himport_prepare(fieldset_name, *fields)

Each method holds @monitor across the server command AND its registry mutation: the two must be atomic with respect to other threads, otherwise a himport_set failing between another thread's DISCARD reply and its registry delete would still see the schema and re-prepare, resurrecting the fieldset the discard just removed. @monitor is reentrant, so the nested send_command/himport_prepare calls re-enter it safely.

[ GitHub ]

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

def himport_prepare(fieldset_name, *fields)
  fields.flatten!(1)
  @monitor.synchronize do
    reply = super(fieldset_name, fields)
    @himport_fieldsets[fieldset_name.to_s] = fields.dup.freeze
    reply
  end
end

#himport_set(key, fieldset_name, *values)

[ GitHub ]

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

def himport_set(key, fieldset_name, *values)
  @monitor.synchronize do
    super
  rescue CommandError => error
    fields = @himport_fieldsets[fieldset_name.to_s]
    raise unless @himport_auto_prepare && fields && error.message.include?("no such fieldset")

    himport_prepare(fieldset_name, fields)
    # `super` (not himport_set) so a second failure propagates instead of recovering again.
    super
  end
end

#id

[ GitHub ]

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

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

#initialize_client(options) (private)

[ GitHub ]

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

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 140

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

#pipelined(exception: true)

[ GitHub ]

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

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 258

def send_blocking_command(command, timeout, &block)
  synchronize do |client|
    client.blocking_call_v(timeout, command, &block)
  end
rescue ::RedisClient::Error => error
  Client.translate_error!(error)
end

#send_command(command, &block) (private)

[ GitHub ]

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

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

#synchronize (private)

All access to @client funnels through here: it serializes on @monitor and applies the RESP3 protocol fallback. Routing pipelined/multi/watch (which all call synchronize) through the same path means they fall back to RESP2 against pre-HELLO servers just like single commands do.

[ GitHub ]

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

def synchronize
  @monitor.synchronize do
    with_protocol_fallback do
      yield(@client)
    end
  end
end

#with {|_self| ... }

Yields:

  • (_self)

Yield Parameters:

  • _self (Redis)

    the object that the method was called on

[ GitHub ]

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

def with
  yield self
end

#with_protocol_fallback (private)

We default to RESP3. Servers that don't support it reject the HELLO 3 handshake (most notably Redis < 6.0, which has no HELLO command). Rebuild the client as RESP2 once so those servers keep working without the user setting protocol: 2.

This is the single fallback point for every client type. Each one surfaces the resp3-unsupported error here untranslated (still a RedisClient::Error): standalone/distributed via Redis::Client#call_v et al., sentinel via the plain RedisClient (which never translates), and cluster via Redis::Cluster::Client#handle_errors. Because every @client access — single commands, pipelined, multi, watch, and the pub/sub socket — flows through #synchronize, wrapping it here covers them all.

Must be called while holding @monitor: it closes and replaces @client, so it has to be serialized with the command execution that uses @client. The retried block re-reads @client, so callers must reference the rebuilt instance (via the synchronize block argument), not a cached one.

[ GitHub ]

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

def with_protocol_fallback
  yield
rescue ::RedisClient::Error => error
  if @options.fetch(:protocol, 3).to_i == 3 && Client.resp3_unsupported?(error)
    @options = @options.merge(protocol: 2)
    @client.close
    @client = build_client
    # Warn only once the RESP2 client is actually in place — if the rebuild itself raises we
    # haven't really fallen back. Fires once per client: @options[:protocol] is now 2, so this
    # branch never re-enters. Passing `protocol: 2` explicitly skips it (and silences this).
    warn("Redis: the server does not support RESP3 (the HELLO 3 handshake failed); falling back " \
         "to RESP2. Pass `protocol: 2` to select RESP2 explicitly and silence this warning.")
    retry
  end

  raise
end

#without_reconnect(&block)

Run code without the client reconnecting

[ GitHub ]

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

def without_reconnect(&block)
  # Route through #synchronize like every other @client access: it holds @monitor and applies the
  # RESP3->RESP2 fallback. disable_reconnection establishes the connection eagerly, so if that
  # handshake fails the fallback rebuilds @client and the whole block re-runs against the new
  # (RESP2) client — keeping disable_reconnection bound to the live @client rather than a discarded
  # one. Referencing the block argument (not @client) is what makes the retry pick up the rebuild.
  synchronize do |client|
    client.disable_reconnection(&block)
  end
end