Class: Redis
Overview
The module below is a direct, function-by-function port of xxHash's XXH3-64 (https://github.com/Cyan4973/xxHash, v0.8.3), reproducing its algorithm, constants, and secret table. xxHash is distributed under the following license, reproduced here per its "redistributions of source code must retain" requirement (see LICENSE for this project's own MIT license, which covers everything else in this repository):
xxHash Library
Copyright (c) 2012-2021 Yann Collet
All rights reserved.
BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Constant Summary
-
BASE_PATH =
# File 'lib/redis.rb', line 10__dir__ -
Deprecated =
# File 'lib/redis.rb', line 11Class.new(StandardError)
-
SERVER_URL_OPTIONS =
# File 'lib/redis.rb', line 39%i(url host port path).freeze
-
VERSION =
# File 'lib/redis/version.rb', line 4'6.0.0'
::Redis::Commands::Json - Included
JSON_SET_FPHA_TYPES, NumincrbyNormalize, TypeNormalize
::Redis::Commands::Search - Included
Commands - Included
Boolify, BoolifyBoolean, BoolifySet, EMPTY_STREAM_RESPONSE, Floatify, FloatifyArray, FloatifyPair, FloatifyPairs, Hashify, HashifyArrayInfo, HashifyClusterNodeInfo, HashifyClusterNodes, HashifyClusterSlaves, HashifyClusterSlotStats, HashifyClusterSlots, HashifyFunctionList, HashifyFunctionStats, HashifyInfo, HashifyStreamAutoclaim, HashifyStreamAutoclaimJustId, HashifyStreamEntries, HashifyStreamPendingDetails, HashifyStreamPendings, HashifyStreams, HashifyVectorEmbeddingRaw, HashifyVectorLinksWithScores, HashifyVectorScores, HashifyVectorScoresWithAttribs, Noop, Pairify
Class Attribute Summary
Class Method Summary
- .deprecate!(message)
-
.new(options = {}) ⇒ Redis
constructor
Create a new client instance.
Instance Attribute Summary
-
#connected? ⇒ Boolean
readonly
Test whether or not the client is connected.
::Redis::Commands::Pubsub - Included
Instance Method Summary
- #_client
-
#close
(also: #disconnect!)
Disconnect the client as quickly and silently as possible.
- #connection
-
#disconnect!
Alias for #close.
- #dup(**option_overrides)
- #himport_discard(fieldset_name)
- #himport_discard_all
-
#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.
- #himport_set(key, fieldset_name, *values)
- #id
- #inspect
-
#keyspace_notifications(error_handler: nil, reconnect_attempts: KeyspaceNotifications::Manager::DEFAULT_RECONNECT_ATTEMPTS) ⇒ KeyspaceNotifications::Manager
Build a keyspace-notification manager.
- #pipelined(exception: true)
- #with {|_self| ... }
-
#without_reconnect(&block)
Run code without the client reconnecting.
- #_subscription(method, timeout, channels, block) private
-
#build_client
private
Builds @client from @options and applies any instance-level settings (socket inheritance) that live outside @options.
- #initialize_client(options) private
- #send_blocking_command(command, timeout, &block) private
- #send_command(command, &block) private
-
#synchronize
private
All access to @client funnels through here: it serializes on @monitor and applies the RESP3 protocol fallback.
-
#with_protocol_fallback
private
We default to RESP3.
Commands - Included
| #call | Sends a command to |
| #sentinel | Interact with the sentinel command (masters, master, slaves, failover). |
| #method_missing | |
::Redis::Commands::VectorSets - Included
| #vadd | Add a new element into a vector set, or update its vector if it already exists. |
| #vcard | Return the number of elements in a vector set. |
| #vdim | Return the number of dimensions of the vectors in a vector set. |
| #vemb | Return the approximate vector associated with an element in a vector set. |
| #vgetattr | Return the JSON attributes associated with an element in a vector set. |
| #vinfo | Return metadata and internal details about a vector set, including size, dimensions, quantization type, and graph structure. |
| #vismember | Check if an element exists in a vector set. |
| #vlinks | Return the neighbors of an element in a vector set, one entry per layer of the HNSW graph. |
| #vrandmember | Return one or more random elements from a vector set. |
| #vrange | Return the elements of a vector set within a lexicographical range, in lexicographical (byte-by-byte) order. |
| #vrem | Remove an element from a vector set. |
| #vsetattr | Associate JSON attributes with an element in a vector set, update them, or delete them. |
| #vsim | Return elements similar to a given vector or element, by approximate (HNSW) or exact ( |
::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. |
| #delex | Delete a key, optionally only if its current value or value digest matches a condition. |
| #digest | Compute a digest of the string value stored at a key, suitable for later comparison via SET's |
| #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. |
| #lcs | Find the longest common subsequence of the strings stored at two keys. |
| #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 ( |
::Redis::Commands::Streams - Included
| #xack | Removes one or multiple entries from the pending entries list of a stream consumer group. |
| #xackdel | Acknowledges and conditionally deletes one or more entries for a stream consumer group, in a single atomic operation. |
| #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. |
| #xdelex | Delete entries by entry ids, with control over consumer group PEL references. |
| #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. |
| #xsetid | Set the last entry id of the stream, and optionally its entries-added counter and maximal deleted entry id. |
| #xtrim | Trims older entries of the stream if needed. |
| #_xread, #xstream_ref_policy_token | |
::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. |
| #zintercard | Get the number of members in 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. |
| #sintercard | Get the number of members in the intersection of 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. |
| #waitaof | Block until the write commands previously sent on this connection have been fsynced to the append-only file of the local server and/or of the given number of replicas. |
::Redis::Commands::Search - Included
| #create_index | Create an index and return a high-level |
| #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 |
| #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. |
| #fcall | Invoke a |
| #fcall_ro | Invoke a read-only |
| #function | Manage Redis Functions libraries. |
| #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 |
| #json_arrindex | Return the index of the first occurrence of a scalar |
| #json_arrinsert | Insert one or more values into the array at |
| #json_arrlen | Return the length of the array at |
| #json_arrpop | Remove and return an element from the array at |
| #json_arrtrim | Trim the array at |
| #json_clear | Clear the container and numeric value(s) at |
| #json_debug_memory | Report the size in bytes of the JSON value(s) at |
| #json_del | Delete the value(s) at |
| #json_forget | Delete the value(s) at |
| #json_get | Get the JSON value(s) at one or more |
| #json_merge | Merge |
| #json_mget | Get the values at a single |
| #json_mset | Set one or more JSON values atomically, one per |
| #json_numincrby | Increment the numeric value(s) at |
| #json_objkeys | Return the key names of the JSON object(s) at |
| #json_objlen | Return the number of keys in the JSON object(s) at |
| #json_set | Set the JSON value at |
| #json_strappend | Append |
| #json_strlen | Return the length of the JSON string(s) at |
| #json_toggle | Toggle the boolean value(s) at |
| #json_type | Return the type name of the value(s) at |
| #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. |
| #sort_ro | Sort the elements in a list, set or sorted set without storing the result. |
| #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, #_sort | |
::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. |
| #hgetdel | Get the value of one or more hash fields and delete them. |
| #hgetex | Get the value of one or more hash fields and optionally set their expiration. |
| #himport_discard | Remove |
| #himport_discard_all | Remove all fieldsets from this connection's session. |
| #himport_prepare | Register an ordered list of hash field names under |
| #himport_set | Create or fully replace the hash at |
| #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. |
| #hsetex | Set the value of one or more hash fields, and optionally their expiration. |
| #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 ( |
::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 |
| #cluster | Sends |
::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 |
| #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 |
Constructor Details
.new(options = {}) ⇒ Redis
Create a new client instance
# File 'lib/redis.rb', line 76
def initialize( = {}) @monitor = Monitor.new @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!() unless silence_deprecations if raise_deprecations raise Deprecated, else ::Kernel.warn() end end end
Instance Attribute Details
#connected? ⇒ Boolean (readonly)
Test whether or not the client is connected
# 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 304
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 # Capture before use: the subscribed thread's teardown nils the ivar # concurrently, and reading it twice would turn that race into a # NoMethodError on nil instead of the SubscriptionError callers handle. client = @subscription_client unless client raise SubscriptionError, "This client is not subscribed" end 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.
# File 'lib/redis.rb', line 226
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.
# File 'lib/redis.rb', line 114
def close @client.close @subscription_client&.close end
#connection
[ GitHub ]# File 'lib/redis.rb', line 155
def connection { host: @client.host, port: @client.port, db: @client.db, id: id, location: "#{@client.host}:#{@client.port}" } end
#disconnect!
Alias for #close.
# File 'lib/redis.rb', line 118
alias disconnect! close
#dup(**option_overrides)
[ GitHub ]# File 'lib/redis.rb', line 144
def dup(**option_overrides) # 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. # Explicit overrides win — keyspace_notifications relies on this to disable transport # retries on the connection its manager owns. self.class.new(@options.merge(inherit_socket: @inherit_socket, himport_auto_prepare: @himport_auto_prepare, **option_overrides)) end
#himport_discard(fieldset_name)
[ GitHub ]# File 'lib/redis.rb', line 205
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 213
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.
# File 'lib/redis.rb', line 182
def himport_prepare(fieldset_name, *fields) fields.flatten!(1) fields.map! { |field| field.dup.freeze } @monitor.synchronize do reply = super(fieldset_name, fields) @himport_fieldsets[fieldset_name.to_s] = fields.freeze reply end end
#himport_set(key, fieldset_name, *values)
[ GitHub ]# File 'lib/redis.rb', line 192
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..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 ]#inspect
[ GitHub ]#keyspace_notifications(error_handler: nil, reconnect_attempts: KeyspaceNotifications::Manager::DEFAULT_RECONNECT_ATTEMPTS) ⇒ KeyspaceNotifications::Manager
Build a keyspace-notification manager. The manager owns a dedicated connection (duplicated from this client's options) and a background listener thread; the calling client remains fully usable for commands.
# File 'lib/redis/keyspace_notifications.rb', line 45
def keyspace_notifications(error_handler: nil, reconnect_attempts: KeyspaceNotifications::Manager::DEFAULT_RECONNECT_ATTEMPTS) # The manager is the sole owner of reconnection timing: transport-level # retries are disabled on the owned connection, or the source client's own # ladder would run inside every one of the manager's connect attempts. KeyspaceNotifications::Manager.new( redis: dup(reconnect_attempts: 0), error_handler: error_handler, reconnect_attempts: reconnect_attempts ) 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, client: client, exception: exception) end end end
#send_blocking_command(command, timeout, &block) (private)
[ GitHub ]# File 'lib/redis.rb', line 263
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 255
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.
# File 'lib/redis.rb', line 247
def synchronize @monitor.synchronize do with_protocol_fallback do yield(@client) end end end
#with {|_self| ... }
# 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.
# File 'lib/redis.rb', line 286
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
# 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