### Keys Operations Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Examples for setting, getting, and listing keys in Redis. ```APIDOC ## Keys Operations ### Description Provides methods for interacting with keys in Redis, including setting values, retrieving values, and listing all keys. ### Method `r.set(key, value)` `r.get(key)` `r.keys` ### Endpoint N/A (Client-side library methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby r.set("redis_db", "great k / v storage") r.get("redis_db") r.keys ``` ### Response #### Success Response (200) - `r.set`: OK - `r.get`: The value associated with the key (string) - `r.keys`: An array of all keys in the database (array of strings) #### Response Example ``` # For r.get("redis_db") "great k / v storage" # For r.keys ["redis_db"] ``` ``` -------------------------------- ### Install redis-clustering Gem Source: https://github.com/redis/redis-rb/blob/master/cluster/README.md Install the gem using the provided command. This is the first step before using the Redis::Cluster client. ```bash $ gem install redis-clustering ``` -------------------------------- ### Basic String Set and Get Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates the fundamental set and get operations for string values in Redis. ```ruby require "redis" redis = Redis.new # Basic set / get redis.set("name", "Alice") # => "OK" redis.get("name") # => "Alice" ``` -------------------------------- ### String Manipulation Utilities Source: https://context7.com/redis/redis-rb/llms.txt Provides examples for appending to strings, getting their length, and retrieving or setting substrings. ```ruby # String utilities redis.append("name", " Smith") # => 11 (new length) redis.strlen("name") # => 11 redis.getrange("name", 0, 4) # => "Alice" redis.setrange("name", 6, "Jones") # => 11 ``` -------------------------------- ### Execute Redis SET and GET Commands Source: https://github.com/redis/redis-rb/blob/master/README.md Demonstrates basic Redis command execution using the client's methods, which mirror the command names. ```ruby redis.set("mykey", "hello world") # => "OK" redis.get("mykey") # => "hello world" ``` -------------------------------- ### Install redis-rb Gem Source: https://github.com/redis/redis-rb/blob/master/README.md Install the redis-rb gem using the RubyGems package manager. ```bash gem install redis ``` -------------------------------- ### Redis Pub/Sub with Ruby Source: https://context7.com/redis/redis-rb/llms.txt Examples for publishing messages to channels and subscribing to receive them. Includes basic subscribe, message handling, unsubscribe, pattern subscription, and subscribe with timeout. ```ruby require "redis" # Publisher (separate connection) publisher = Redis.new publisher.publish("news:tech", "Redis 8.0 released!") # => 1 (number of receivers) ``` ```ruby # Subscriber subscriber = Redis.new subscriber.subscribe("news:tech", "news:sports") do |on| on.subscribe do |channel, count| puts "Subscribed to #{channel} (#{count} total)" end on.message do |channel, message| puts "#{channel}: #{message}" subscriber.unsubscribe if message == "quit" end on.unsubscribe do |channel, count| puts "Unsubscribed from #{channel}" end end ``` ```ruby # Pattern subscription (glob patterns) subscriber.psubscribe("news:*") do |on| on.pmessage do |pattern, channel, message| puts "[#{pattern}] #{channel}: #{message}" end end ``` ```ruby # Subscribe with timeout (raises Redis::TimeoutError after N seconds of silence) redis = Redis.new(reconnect_attempts: 0) redis.subscribe_with_timeout(10, "heartbeat") do |on| on.message { |_ch, msg| puts msg } end ``` ```ruby # Shard pub/sub (Redis 7+ cluster sharding) redis.spublish("shard:channel", "sharded message") redis.ssubscribe("shard:channel") do |on| on.message { |ch, msg| puts msg } end ``` ```ruby # Inspect pub/sub state redis.pubsub("channels", "news:*") # => ["news:tech", "news:sports"] redis.pubsub("numsub", "news:tech") # => ["news:tech", 1] redis.pubsub("numpat") # => 0 ``` -------------------------------- ### Daily Active User Tracking with Redis Bitmaps Source: https://context7.com/redis/redis-rb/llms.txt Example of using `setbit` and `bitcount` for daily active user tracking, where each bit represents a user ID. ```ruby today = Time.now.strftime("active:%Y%m%d") redis.setbit(today, 42, 1) redis.setbit(today, 99, 1) redis.bitcount(today) ``` -------------------------------- ### Expiration Operations Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Examples for setting time-to-live for keys in Redis. ```APIDOC ## Expiration Operations ### Description Enables setting expiration times for keys, causing them to be automatically deleted after a specified duration. ### Method `r.expire(key, seconds)` `r.expireat(key, timestamp)` ### Endpoint N/A (Client-side library methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby r.expire("redis_db", 100) # Expires in 100 seconds r.expireat("redis_db", Time.now.to_i + 30) # Expires in 30 seconds from now ``` ### Response #### Success Response (200) - `r.expire`: true if the timeout was set, false if the key does not exist. - `r.expireat`: true if the timeout was set, false if the key does not exist. #### Response Example ``` # For r.expire("redis_db", 100) true # For r.expireat("redis_db", Time.now.to_i + 30) true ``` ``` -------------------------------- ### Bulk String Set and Get Operations Source: https://context7.com/redis/redis-rb/llms.txt Shows how to set multiple key-value pairs atomically (MSETNX) or individually (MSET), and retrieve multiple values (MGET, MAPPED_MGET). ```ruby # Bulk set / get redis.mset("k1", "v1", "k2", "v2", "k3", "v3") # => "OK" redis.mget("k1", "k2", "k3") # => ["v1", "v2", "v3"] redis.mapped_mget("k1", "k2") # => {"k1"=>"v1", "k2"=>"v2"} redis.mapped_mset("k4" => "v4", "k5" => "v5") # => "OK" redis.msetnx("new1", "a", "new2", "b") # => true (all set) or false ``` -------------------------------- ### Redis Scripting with Lua (eval, evalsha) Source: https://context7.com/redis/redis-rb/llms.txt Examples for executing Lua scripts atomically on the Redis server. Covers inline evaluation and using KEYS/ARGV for passing arguments. ```ruby require "redis" redis = Redis.new # Inline eval — simple atomic get-and-increment result = redis.eval("return redis.call('INCR', KEYS[1])", ["page:views"]) # => 1 ``` ```ruby # Eval with KEYS and ARGV result = redis.eval( "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end", keys: ["lock:resource"], argv: ["owner-token-abc"] ) # => 1 (deleted) or 0 (token mismatch — someone else holds the lock) ``` ```ruby # Hash-based argument form redis.eval( "return { KEYS[1], KEYS[2], ARGV[1] }", keys: ["k1", "k2"], argv: ["hello"] ) # => ["k1", "k2", "hello"] ``` -------------------------------- ### Get and Modify String Operations Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates commands that retrieve a value and modify the key simultaneously, including GETSET, GETDEL, GETEX, and PERSIST. ```ruby # Get-and-modify redis.getset("name", "Bob") # => "Alice" (returns old, sets new) redis.getdel("name") # => "Bob" (returns and deletes) redis.getex("session", persist: true) # fetch and remove TTL redis.getex("session", ex: 7200) # fetch and reset TTL ``` -------------------------------- ### Hash Operations Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Examples for storing and retrieving hash data structures in Redis. ```APIDOC ## Hash Operations ### Description Provides methods for managing hash data types in Redis, allowing storage of field-value pairs within a single key. ### Method `r.hset(hash, key, value)` `r.hget(hash, key)` `r.hmset(hash, key1, value1, key2, value2, ...)` `r.hvals(hash)` `r.hlen(hash)` ### Endpoint N/A (Client-side library methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby r.hset("hash_dt", "key1", true) r.hget("hash_dt", "key1") r.hmset("hash_dt", :key2, "value2", :key3, "value3") r.hvals("hash_dt") r.hlen("hash_dt") ``` ### Response #### Success Response (200) - `r.hset`: true if the field is a new field in the hash, false if the field already exists. - `r.hget`: The value of the field, or nil if the field does not exist. - `r.hmset`: OK - `r.hvals`: An array of values in the hash. - `r.hlen`: The number of fields in the hash. #### Response Example ``` # For r.hset("hash_dt", "key1", true) true # For r.hget("hash_dt", "key1") "true" # For r.hmset(...) OK # For r.hvals("hash_dt") ["true", "value2", "value3"] # For r.hlen("hash_dt") 3 ``` ``` -------------------------------- ### Manage Redis Clients Source: https://context7.com/redis/redis-rb/llms.txt Use `client` commands to list connected clients, get or set the client name, and kill client connections. ```ruby redis.client(:list) redis.client(:getname) redis.client(:setname, "my-worker") redis.client(:kill, "127.0.0.1:54321") ``` -------------------------------- ### Sorted Set Operations Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Examples for querying sorted sets in Redis with limits and scores. ```APIDOC ## Sorted Set Operations ### Description Demonstrates querying sorted sets with options for limiting results and including scores. ### Method `r.zrangebyscore(key, min, max, options)` ### Endpoint N/A (Client-side library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby # With limit r.zrangebyscore("key", "-inf", "+inf", :limit => [0, 1]) # With scores r.zrangebyscore("key", "-inf", "+inf", :with_scores => true) ``` ### Response #### Success Response (200) - Returns an array of elements within the specified score range. Options can modify the output to include scores or limit the number of returned elements. ``` -------------------------------- ### Key Metadata and Renaming Source: https://context7.com/redis/redis-rb/llms.txt Shows how to retrieve the type of a key, get a random key, and rename keys, including conditional renaming with RENAMENX. ```ruby # Key metadata redis.type("temp") # => "string" redis.randomkey # => some random key name redis.rename("temp", "permanent") redis.renamenx("permanent", "final") # rename only if target doesn't exist => true/false ``` -------------------------------- ### Basic Hash Set and Get Source: https://context7.com/redis/redis-rb/llms.txt Introduces the fundamental operations for storing and retrieving field-value pairs within a Redis hash. ```ruby require "redis" redis = Redis.new ``` -------------------------------- ### Configure Redis Server Settings Source: https://context7.com/redis/redis-rb/llms.txt Use `config` commands to get, set, and reset Redis server configuration parameters. Changes made with `config set` are persistent across restarts if saved. ```ruby redis.config(:get, "maxmemory") redis.config(:set, "maxmemory", "100mb") redis.config(:resetstat) ``` -------------------------------- ### Get Redis Server Information Source: https://context7.com/redis/redis-rb/llms.txt Use the `info` command to retrieve various details about the Redis server, such as version, memory usage, and persistence status. The result is parsed into a Hash. ```ruby require "redis" redis = Redis.new info = redis.info puts info["redis_version"] puts info["used_memory_human"] redis.info("memory") redis.info("commandstats") ``` -------------------------------- ### Load and Execute Lua Scripts by SHA Source: https://context7.com/redis/redis-rb/llms.txt Load a Lua script into Redis to get its SHA digest, then execute the script using its SHA. This avoids resending the script body on subsequent calls. ```ruby lua_script = <<~LUA local val = redis.call('GET', KEYS[1]) redis.call('SET', KEYS[1], val .. ARGV[1]) return redis.call('GET', KEYS[1]) LUA sha = redis.script(:load, lua_script) redis.set("greeting", "Hello") redis.evalsha(sha, keys: ["greeting"], argv: [", World!"]) ``` ```ruby redis.script(:exists, sha) redis.script(:exists, [sha, "nonexistent"]) redis.script(:flush) ``` -------------------------------- ### Initialization Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Demonstrates how to initialize the Redis client library. ```APIDOC ## Initialization ### Description Initializes a new Redis client instance. ### Method `Redis.new` ### Endpoint N/A (Client-side library method) ### Request Example ```ruby require "redis" r = Redis.new ``` ### Response N/A (Initializes an object) ``` -------------------------------- ### Connect to Redis with Various Options Source: https://context7.com/redis/redis-rb/llms.txt Instantiate Redis with different connection parameters like host, port, database, URL, Unix socket, username/password, SSL/TLS, timeouts, and reconnect strategies. Supports Hiredis driver for performance. ```ruby require "redis" # Default: localhost:6379, db 0 redis = Redis.new # Explicit host/port/db redis = Redis.new(host: "10.0.1.1", port: 6380, db: 15) # Via Redis URL (password URL-encoded with CGI.escape if it contains special chars) redis = Redis.new(url: "redis://:p4ssw0rd@10.0.1.1:6380/15") # Unix socket redis = Redis.new(path: "/tmp/redis.sock") # ACL user + password redis = Redis.new(username: "appuser", password: "mysecret") # SSL/TLS with mutual TLS redis = Redis.new( url: "rediss://:p4ssw0rd@10.0.1.1:6381/15", ssl_params: { ca_file: "/path/to/ca.crt", cert: OpenSSL::X509::Certificate.new(File.read("client.crt")), key: OpenSSL::PKey::RSA.new(File.read("client.key")) } ) # Custom timeouts (seconds) redis = Redis.new( connect_timeout: 0.2, read_timeout: 1.0, write_timeout: 0.5 ) # Reconnect attempts — integer or array of sleep durations between retries redis = Redis.new(reconnect_attempts: [0, 0.25, 1]) # Hiredis driver for large replies / big pipelines redis = Redis.new(driver: :hiredis) puts redis.ping # => "PONG" puts redis.id # => "redis://127.0.0.1:6379/0" puts redis.connection # => { host: "127.0.0.1", port: 6379, db: 0, id: "...", location: "127.0.0.1:6379" } ``` -------------------------------- ### Pipelining with Immediate Command Execution Source: https://github.com/redis/redis-rb/blob/master/README.md Demonstrates that calling methods on the original client object within a pipeline block results in immediate command execution. ```ruby redis.pipelined do |pipeline| pipeline.set "foo", "bar" redis.incr "baz" # => 1 end # => ["OK"] ``` -------------------------------- ### Get Geohash and Perform Radius Search with Redis Geo Commands Source: https://context7.com/redis/redis-rb/llms.txt Use `geohash` to get the geohash representation of a member and `georadius` to find members within a specified radius. ```ruby redis.geohash("cities", "Chicago") redis.georadius("cities", -90.0, 38.0, 2000, "km", sort: "asc", count: 10, options: "WITHCOORD WITHDIST" ) ``` -------------------------------- ### Delete Operation Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Example for deleting a key from Redis. ```APIDOC ## Delete Operation ### Description Removes a key and its associated value from the Redis database. ### Method `r.del(key)` ### Endpoint N/A (Client-side library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby r.del("redis_db") ``` ### Response #### Success Response (200) - Returns the number of keys that were removed (always 1 if the key existed). #### Response Example ``` 1 ``` ``` -------------------------------- ### Initialize Redis Connection Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Establishes a connection to the Redis server. Ensure Redis is running before executing. ```ruby require "redis" r = Redis.new ``` -------------------------------- ### Server Commands Source: https://context7.com/redis/redis-rb/llms.txt Inspect, configure, and administer the Redis server instance. ```APIDOC ## Server Commands (info, config, client, flushdb, monitor, time) Inspect, configure, and administer the Redis server instance. ```ruby require "redis" redis = Redis.new # Server info (returns a parsed Hash) info = redis.info puts info["redis_version"] # => "7.2.4" puts info["used_memory_human"] # => "1.23M" redis.info("memory") # memory section only redis.info("commandstats") # per-command statistics Hash # Configuration redis.config(:get, "maxmemory") # => {"maxmemory" => "0"} redis.config(:set, "maxmemory", "100mb") # => "OK" redis.config(:resetstat) # => "OK" # Client list and management redis.client(:list) # => [{"id"=>"3", "addr"=>"127.0.0.1:54321", ...}, ...] redis.client(:getname) # => nil (or the connection name) redis.client(:setname, "my-worker") redis.client(:kill, "127.0.0.1:54321") ``` ``` -------------------------------- ### Counter Operations Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Examples for incrementing and decrementing numeric values in Redis. ```APIDOC ## Counter Operations ### Description Allows atomic incrementing and decrementing of integer values stored in Redis. ### Method `r.incr(key)` `r.decr(key)` `r.incrby(key, increment)` `r.decrby(key, decrement)` ### Endpoint N/A (Client-side library methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby r.incr("redis_db") r.decr("couch_db") r.incrby("redis_db", 99) r.decrby("couch_db", -101) ``` ### Response #### Success Response (200) - Returns the value of the counter after the increment or decrement operation. #### Response Example ``` # For r.incr("redis_db") 1 # For r.decr("couch_db") -1 # For r.incrby("redis_db", 99) 100 # For r.decrby("couch_db", -101) 100 ``` ``` -------------------------------- ### Redis Pipelining in Ruby Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates how to batch multiple Redis commands into a single network round-trip using `pipelined`. Shows basic pipelining, capturing individual replies via futures, and handling errors without exceptions. ```ruby require "redis" redis = Redis.new # Basic pipeline — all replies returned as an array results = redis.pipelined do |pipe| pipe.set("key1", "val1") pipe.set("key2", "val2") pipe.incr("counter") pipe.expire("key1", 300) end # => ["OK", "OK", 1, true] # Capture futures for individual reply access set_future = incr_future = nil redis.pipelined do |pipe| set_future = pipe.set("foo", "bar") incr_future = pipe.incr("baz") end set_future.value # => "OK" incr_future.value # => 1 # Non-raising pipeline: errors in results instead of exceptions results = redis.pipelined(exception: false) do |pipe| pipe.set("key1", "value1") pipe.lpush("key1", "oops") # WRONGTYPE error — key1 is a string pipe.set("key2", "value2") end # => ["OK", #, "OK"] results.each do |r| if r.is_a?(Redis::CommandError) puts "Command failed: #{r.message}" end end ``` -------------------------------- ### Slow Log Source: https://context7.com/redis/redis-rb/llms.txt Commands for interacting with the Redis slow log, including getting its length, retrieving entries, and resetting it. ```APIDOC ## Slow Log ### Description Commands for interacting with the Redis slow log, including getting its length, retrieving entries, and resetting it. ### Methods - `redis.slowlog("len")` - `redis.slowlog("get", count)` - `redis.slowlog("reset")` ### Examples ```ruby redis.slowlog("len") # => 3 redis.slowlog("get", 10) # => array of slow log entries redis.slowlog("reset") # => "OK" ``` ``` -------------------------------- ### Redis::Distributed Key Routing and Operations Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates automatic key routing, adding nodes, finding nodes for keys, using hash tags for co-location, and running operations on all nodes. ```ruby # Keys are automatically routed to the correct node dist.set("user:1:name", "Alice") dist.set("user:2:name", "Bob") dist.get("user:1:name") # => "Alice" (retrieved from correct shard) ``` ```ruby # Add a node at runtime dist.add_node("redis://127.0.0.1:6382") ``` ```ruby # Find which node holds a key node = dist.node_for("user:1:name") # => # ``` ```ruby # Force keys to the same shard with hash tags {tag} dist.mset("{user:1}name", "Alice", "{user:1}email", "alice@example.com") dist.mget("{user:1}name", "{user:1}email") # => ["Alice", "alice@example.com"] ``` ```ruby # Operations run on ALL nodes dist.dbsize # => [100, 200, 150] (per-node key counts) dist.flushdb dist.ping # => ["PONG", "PONG", "PONG"] ``` -------------------------------- ### Set and Get Key-Value Pairs Source: https://github.com/redis/redis-rb/wiki/Redis-rb-Overview Stores and retrieves string values associated with keys. Supports basic CRUD operations. ```ruby r.set("redis_db", "great k / v storage") # => OK r.get("redis_db") # => "great k / v storage" r.keys # => ["redis_db"] ``` -------------------------------- ### Key Copying and Moving Source: https://context7.com/redis/redis-rb/llms.txt Illustrates copying keys within the same database or to a different database using COPY, and moving keys between databases using MOVE. ```ruby # Copying and moving redis.copy("final", "backup") # => true redis.copy("final", "remote", db: 2) # copy to another DB redis.move("backup", 1) # move to DB 1 => true ``` -------------------------------- ### Redis Slow Log Management Source: https://context7.com/redis/redis-rb/llms.txt Commands to manage and retrieve the Redis slow log, including getting its length, entries, and resetting it. ```ruby redis.slowlog("len") # => 3 ``` ```ruby redis.slowlog("get", 10) # => array of slow log entries ``` ```ruby redis.slowlog("reset") # => "OK" ``` -------------------------------- ### Count Approximate Cardinality with Redis HyperLogLog Source: https://context7.com/redis/redis-rb/llms.txt Use `pfcount` to get the approximate number of unique elements in one or more HyperLogLog keys. ```ruby redis.pfcount("unique-visitors:2024-01-15") redis.pfcount("unique-visitors:2024-01-15", "unique-visitors:2024-01-16") ``` -------------------------------- ### Redis Transactions with WATCH/MULTI/EXEC Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates how to use WATCH to monitor keys and execute MULTI/EXEC for atomic operations. The transaction is aborted if watched keys change before EXEC. ```ruby loop do result = redis.watch("balance") do current = redis.get("balance").to_i if current >= 50 redis.multi do |tx| tx.set("balance", current - 50) tx.incr("withdrawals") end else redis.unwatch break "Insufficient funds" end end break if result # multi returned array => success; nil => retry end ``` -------------------------------- ### Connect to Default Redis Instance Source: https://github.com/redis/redis-rb/blob/master/README.md Instantiate the Redis client to connect to a Redis server with default configuration (localhost, port 6379). ```ruby require "redis" redis = Redis.new ``` -------------------------------- ### Connect to Remote Redis Instance Source: https://github.com/redis/redis-rb/blob/master/README.md Connect to a Redis instance on a specific host and port, and select a database. ```ruby redis = Redis.new(host: "10.0.1.1", port: 6380, db: 15) ``` -------------------------------- ### Redis Hash Commands in Ruby Source: https://context7.com/redis/redis-rb/llms.txt Use these commands to manage hash fields and values. Supports setting, getting, deleting, and checking for field existence. ```ruby redis.hset("user:1", "name", "Alice", "age", "30") ``` ```ruby redis.hset("user:1", { email: "alice@example.com" }) ``` ```ruby redis.hsetnx("user:1", "role", "admin") ``` ```ruby redis.hmset("user:1", "city", "NYC", "plan", "pro") ``` ```ruby redis.hget("user:1", "name") ``` ```ruby redis.hmget("user:1", "name", "age", "missing") ``` ```ruby redis.mapped_hmget("user:1", "name", "email") ``` ```ruby redis.hgetall("user:1") ``` ```ruby redis.hkeys("user:1") ``` ```ruby redis.hvals("user:1") ``` ```ruby redis.hlen("user:1") ``` ```ruby redis.hexists("user:1", "name") ``` ```ruby redis.hset("stats", "views", 0) ``` ```ruby redis.hincrby("stats", "views", 5) ``` ```ruby redis.hincrbyfloat("stats", "rate", 0.75) ``` ```ruby redis.hdel("user:1", "role", "plan") ``` ```ruby redis.hrandfield("user:1") ``` ```ruby redis.hrandfield("user:1", 2) ``` ```ruby redis.hrandfield("user:1", 2, with_values: true) ``` ```ruby redis.hscan_each("user:1", match: "e*") do |field, value| puts "#{field}: #{value}" end ``` ```ruby redis.hexpire("user:1", 300, "session_token") ``` ```ruby redis.httl("user:1", "session_token", "name") ``` ```ruby redis.hpexpire("user:1", 5000, "otp", nx: true) ``` ```ruby redis.hpttl("user:1", "otp") ``` -------------------------------- ### Initialize Redis::Distributed Client Source: https://context7.com/redis/redis-rb/llms.txt Connects to a Redis cluster using a list of node URLs or option hashes. Keys are automatically routed using consistent hashing. ```ruby require "redis" # Connect to a shard cluster via URLs or option hashes nodes = [ "redis://127.0.0.1:6379", "redis://127.0.0.1:6380", "redis://127.0.0.1:6381" ] dist = Redis::Distributed.new(nodes) ``` -------------------------------- ### Configure SSL/TLS Connection with URL Source: https://github.com/redis/redis-rb/blob/master/README.md Enable SSL/TLS support by providing a rediss URL and configuring SSL parameters for the connection context. ```ruby redis = Redis.new( :url => "rediss://:p4ssw0rd@10.0.1.1:6381/15", :ssl_params => { :ca_file => "/path/to/ca.crt" } ) ``` -------------------------------- ### Get Coordinates and Distance with Redis Geo Commands Source: https://context7.com/redis/redis-rb/llms.txt Use `geopos` to retrieve coordinates of members and `geodist` to calculate the distance between two members in specified units. ```ruby redis.geopos("cities", "Chicago") redis.geopos("cities", ["Chicago", "New York"]) redis.geodist("cities", "Chicago", "New York", "km") redis.geodist("cities", "Chicago", "New York", "mi") ``` -------------------------------- ### String Set with Expiry Options Source: https://context7.com/redis/redis-rb/llms.txt Shows how to set string values with various expiry conditions like seconds, milliseconds, only if not exists (NX), only if exists (XX), and retaining TTL. ```ruby # Set with expiry options redis.set("session", "abc123", ex: 3600) # expire in 3600 seconds redis.set("token", "xyz", px: 5000) # expire in 5000 milliseconds redis.set("flag", "1", nx: true) # only if key does not exist => true/false redis.set("flag", "2", xx: true) # only if key exists => true/false redis.set("cached", "data", keepttl: true) # retain existing TTL old = redis.set("counter", "99", get: true) # return old value before overwrite ``` -------------------------------- ### Error Handling with Redis::BaseError Source: https://github.com/redis/redis-rb/blob/master/README.md Catch Redis-related exceptions using `Redis::BaseError` or more specific error classes. This example shows catching a connection error. ```ruby begin redis.ping rescue Redis::BaseError => e e.inspect # => # e.message # => Timed out connecting to Redis on 10.0.1.1:6380 end ``` -------------------------------- ### Configure SSL/TLS with Client Certificate Authentication Source: https://github.com/redis/redis-rb/blob/master/README.md Enable SSL/TLS with mutual TLS authentication by providing CA file, client certificate, and private key. ```ruby redis = Redis.new( :url => "rediss://:p4ssw0rd@10.0.1.1:6381/15", :ssl_params => { :ca_file => "/path/to/ca.crt", :cert => OpenSSL::X509::Certificate.new(File.read("client.crt")), :key => OpenSSL::PKey::RSA.new(File.read("client.key")) } ) ``` -------------------------------- ### Key Expiry Management Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates setting and checking key expiry times in seconds (EXPIRE, TTL) and milliseconds (PEXPIRE, PTTL), including absolute expiry times and retaining TTL. ```ruby # Expiry redis.set("temp", "x") redis.expire("temp", 60) # => true redis.expireat("temp", Time.now.to_i + 120) # => true redis.pexpire("temp", 5000) # milliseconds redis.ttl("temp") # => seconds remaining (-2 = gone, -1 = no expiry) redis.pttl("temp") # => milliseconds remaining redis.expiretime("temp") # => UNIX timestamp of expiry redis.persist("temp") # remove TTL => true ``` -------------------------------- ### String Commands Source: https://context7.com/redis/redis-rb/llms.txt Core key-value operations with expiry options, conditional sets, atomic counters, and bulk operations. ```APIDOC ## String Commands (set, get, mset, incr, append, getex, etc.) Core key-value operations with expiry options, conditional sets, atomic counters, and bulk operations. ```ruby require "redis" redis = Redis.new # Basic set / get redis.set("name", "Alice") # => "OK" redis.get("name") # => "Alice" # Set with expiry options redis.set("session", "abc123", ex: 3600) # expire in 3600 seconds redis.set("token", "xyz", px: 5000) # expire in 5000 milliseconds redis.set("flag", "1", nx: true) # only if key does not exist => true/false redis.set("flag", "2", xx: true) # only if key exists => true/false redis.set("cached", "data", keepttl: true) # retain existing TTL old = redis.set("counter", "99", get: true) # return old value before overwrite # Conditional set redis.setnx("lock", "owner") # => true (set) or false (already exists) redis.setex("temp", 60, "val") # set with TTL in seconds redis.psetex("ms", 500, "v") # set with TTL in milliseconds # Atomic counters redis.set("hits", 0) redis.incr("hits") # => 1 redis.incrby("hits", 10) # => 11 redis.decr("hits") # => 10 redis.decrby("hits", 3) # => 7 redis.incrbyfloat("rate", 1.5) # => 1.5 # Bulk set / get redis.mset("k1", "v1", "k2", "v2", "k3", "v3") # => "OK" redis.mget("k1", "k2", "k3") # => ["v1", "v2", "v3"] redis.mapped_mget("k1", "k2") # => {"k1"=>"v1", "k2"=>"v2"} redis.mapped_mset("k4" => "v4", "k5" => "v5") # => "OK" redis.msetnx("new1", "a", "new2", "b") # => true (all set) or false # String utilities redis.append("name", " Smith") # => 11 (new length) redis.strlen("name") # => 11 redis.getrange("name", 0, 4) # => "Alice" redis.setrange("name", 6, "Jones") # => 11 # Get-and-modify redis.getset("name", "Bob") # => "Alice" (returns old, sets new) redis.getdel("name") # => "Bob" (returns and deletes) redis.getex("session", persist: true) # fetch and remove TTL redis.getex("session", ex: 7200) # fetch and reset TTL ``` ``` -------------------------------- ### Handle Cross-Slot Commands Source: https://github.com/redis/redis-rb/blob/master/cluster/README.md The calling code is responsible for avoiding cross-slot commands. The example shows a `mget` command failing with a `CROSSSLOT` error and how to use hash tags to prevent this. ```ruby redis = Redis::Cluster.new(nodes: %w[redis://127.0.0.1:7000]) redis.mget('key1', 'key2') #=> Redis::CommandError (CROSSSLOT Keys in request don't hash to the same slot) redis.mget('{key}1', '{key}2') #=> [nil, nil] ``` -------------------------------- ### Set and Get Individual Bits with Redis Bitmap Commands Source: https://context7.com/redis/redis-rb/llms.txt Use `setbit` and `getbit` to manipulate individual bits within a Redis string value. Useful for compact boolean flags. ```ruby require "redis" redis = Redis.new redis.setbit("flags", 7, 1) redis.setbit("flags", 15, 1) redis.setbit("flags", 0, 1) redis.getbit("flags", 7) redis.getbit("flags", 1) ``` -------------------------------- ### Redis Set Operations in Ruby Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates basic set operations like adding members, moving members between sets, and performing set algebra (intersection, union, difference). Includes cursor-based scanning for full set traversal. ```ruby redis.sadd("tags:2", "redis", "python") redis.smove("tags:2", "tags:1", "python") # => true # Set algebra redis.sadd("a", 1, 2, 3) redis.sadd("b", 2, 3, 4) redis.sinter("a", "b") # => ["2", "3"] redis.sunion("a", "b") # => ["1", "2", "3", "4"] redis.sdiff("a", "b") # => ["1"] redis.sinterstore("result_inter", "a", "b") # => 2 (stored) redis.sunionstore("result_union", "a", "b") # => 4 redis.sdiffstore("result_diff", "a", "b") # => 1 # Cursor-based full scan redis.sscan_each("a", match: "[123]") do |member| puts member end ``` -------------------------------- ### Add hiredis-client to Gemfile Source: https://github.com/redis/redis-rb/blob/master/README.md Include the hiredis-client gem in your Gemfile to enable the hiredis driver for faster parsing. ```ruby gem "redis" gem "hiredis-client" ``` -------------------------------- ### Re-establish Redis Connection on Passenger Worker Start Source: https://github.com/redis/redis-rb/wiki/redis-rb-on-Phusion-Passenger Add this code to your environment.rb file to ensure a new Redis connection is established when a Passenger worker process is forked. This prevents shared connections between workers. ```ruby if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| # We're in smart spawning mode. if forked # Re-establish redis connection $redis.client.reconnect end end end ``` -------------------------------- ### Connect to Redis Cluster with Hash Options Source: https://github.com/redis/redis-rb/blob/master/cluster/README.md Connect to a Redis cluster by providing nodes as an array of connection URLs. Options can also be specified as a Hash, similar to single server connections. ```ruby # Nodes can be passed to the client as an array of connection URLs. nodes = (7000..7005).map { |port| "redis://127.0.0.1:#{port}" } redis = Redis::Cluster.new(nodes: nodes) # You can also specify the options as a Hash. The options are the same as for a single server connection. (7000..7005).map { |port| { host: '127.0.0.1', port: port } } ``` -------------------------------- ### Redis Streams Operations with Ruby Source: https://context7.com/redis/redis-rb/llms.txt Examples for using Redis Streams, an append-only log data structure. Covers adding entries, reading ranges, blocking reads, consumer groups, acknowledging messages, and stream information. ```ruby require "redis" redis = Redis.new # Add entries to a stream id1 = redis.xadd("events", { type: "login", user: "alice" }) id2 = redis.xadd("events", { type: "purchase", amount: "42" }, maxlen: 10_000, approximate: true) redis.xadd("events", { type: "logout", user: "alice" }, id: "#{Time.now.to_i * 1000}-0") redis.xlen("events") # => 3 ``` ```ruby # Read entries (range) redis.xrange("events") # all entries ascending redis.xrange("events", id1, id2, count: 10) # bounded range redis.xrevrange("events", "+", "-", count: 5) # newest first ``` ```ruby # Read new entries (non-blocking) redis.xread("events", "0-0") # from beginning redis.xread("events", "$", block: 2000) # block up to 2s for new entries ``` ```ruby # Consumer groups redis.xgroup(:create, "events", "processors", "$", mkstream: true) redis.xgroup(:create, "events", "processors", "0") # reprocess from beginning ``` ```ruby # Read as consumer group member entries = redis.xreadgroup("processors", "worker-1", "events", ">", count: 10) # => { "events" => [["1700000000000-0", {"type"=>"login","user"=>"alice"}], ...] } ``` ```ruby # Acknowledge processed entries redis.xack("events", "processors", id1, id2) # => 2 ``` ```ruby # Pending entries report redis.xpending("events", "processors") # => { "count"=>1, "min"=>"...", "max"=>"...", "consumers"=>[...] } redis.xpending("events", "processors", "-", "+", 10) # detailed list ``` ```ruby # Claim stale pending entries (idle > 1 minute) redis.xclaim("events", "processors", "worker-2", 60_000, id1) ``` ```ruby # Auto-claim (scan + claim in one call) redis.xautoclaim("events", "processors", "worker-2", 60_000, "0-0", count: 50) ``` ```ruby # Stream info redis.xinfo(:stream, "events") redis.xinfo(:groups, "events") redis.xinfo(:consumers, "events", "processors") ``` ```ruby # Trim redis.xtrim("events", 1000) # keep latest 1000 redis.xtrim("events", 1000, approximate: true) # approximate trim (~) redis.xtrim("events", "1700000000000-0", strategy: "MINID") # trim by min ID ``` -------------------------------- ### Redis Transactions in Ruby Source: https://context7.com/redis/redis-rb/llms.txt Illustrates how to execute a block of commands atomically using `multi`/`exec`. Also covers optimistic locking with `WATCH` and `UNWATCH` for check-and-set operations. ```ruby require "redis" redis = Redis.new # Atomic MULTI/EXEC block redis.multi do |tx| tx.set("balance", 100) tx.incr("tx-count") tx.lpush("audit-log", "transfer") end # => ["OK", 1, 1] # Optimistic locking with WATCH ``` -------------------------------- ### Instantiate Redis Client with Hiredis Driver Source: https://github.com/redis/redis-rb/blob/master/README.md Specify the hiredis driver explicitly when creating a new Redis client instance to ensure hiredis is used. ```ruby redis = Redis.new(driver: :hiredis) ``` -------------------------------- ### Connect to Redis using URL Source: https://github.com/redis/redis-rb/blob/master/README.md Specify connection options, including authentication, using a redis:// URL. Passwords with special characters should be URL-encoded. ```ruby redis = Redis.new(url: "redis://:p4ssw0rd@10.0.1.1:6380/15") ``` -------------------------------- ### Scripting Source: https://context7.com/redis/redis-rb/llms.txt Details how to execute Lua scripts atomically on the Redis server using EVAL and EVALSHA, including loading scripts by SHA. ```APIDOC ## Scripting (eval, evalsha, script) Execute Lua scripts atomically on the server. Load scripts by SHA for repeated execution. ```ruby require "redis" redis = Redis.new # Inline eval — simple atomic get-and-increment result = redis.eval("return redis.call('INCR', KEYS[1])", ["page:views"]) # => 1 # Eval with KEYS and ARGV result = redis.eval( "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end", keys: ["lock:resource"], argv: ["owner-token-abc"] ) # => 1 (deleted) or 0 (token mismatch — someone else holds the lock) # Hash-based argument form redis.eval( "return { KEYS[1], KEYS[2], ARGV[1] }", keys: ["k1", "k2"], argv: ["hello"] ) # => ["k1", "k2", "hello"] ``` ``` -------------------------------- ### Keyspace Iteration with SCAN Source: https://context7.com/redis/redis-rb/llms.txt Demonstrates cursor-based iteration over keys using SCAN, including pattern matching and type filtering. Avoid KEYS on large datasets in production. ```ruby # Keyspace iteration (cursor-based, safe for large datasets) redis.scan(0, match: "user:*", count: 100) # => ["42", ["user:1", "user:2", "user:5"]] (cursor, keys) redis.scan_each(match: "user:*", type: "hash") do |key| puts key end # Find keys by pattern (avoid on large datasets in production) redis.keys("user:*") # => ["user:1", "user:2", ...] ``` -------------------------------- ### Connect to Redis via Unix Socket Source: https://github.com/redis/redis-rb/blob/master/README.md Establish a connection to a Redis instance listening on a Unix domain socket. ```ruby redis = Redis.new(path: "/tmp/redis.sock") ```