### Install Crystal Redis Library Source: https://context7.com/stefanwille/crystal-redis/llms.txt Instructions for adding the Crystal Redis library to your project's dependencies using shards.yml and installing it. ```yaml dependencies: redis: github: stefanwille/crystal-redis ``` ```bash shards install ``` -------------------------------- ### Manage Redis Hashes with Crystal Source: https://context7.com/stefanwille/crystal-redis/llms.txt Provides examples for performing various operations on Redis hashes using the Crystal Redis client. This includes setting and getting fields, retrieving all fields, and checking for field existence. ```crystal require "redis" redis = Redis.new # Set hash fields redis.hset("user:100", "name", "Alice") redis.hset("user:100", {"email" => "alice@example.com", "age" => "30"}) # Get hash field redis.hget("user:100", "name") # => "Alice" # Get all fields and values redis.hgetall("user:100") # => {"name" => "Alice", "email" => "alice@example.com", "age" => "30"} # Get multiple fields redis.hmget("user:100", "name", "email") # => ["Alice", "alice@example.com"] # Set multiple fields redis.hmset("user:100", {"city" => "NYC", "country" => "USA"}) # Set field only if it doesn't exist redis.hsetnx("user:100", "name", "Bob") # => 0 (field exists) # Check if field exists redis.hexists("user:100", "name") # => 1 # Delete field redis.hdel("user:100", "age") # Get all field names redis.hkeys("user:100") # => ["name", "email", "city", "country"] # Get all values redis.hvals("user:100") # => ["Alice", "alice@example.com", "NYC", "USA"] # Get number of fields redis.hlen("user:100") # => 4 # Increment numeric field redis.hset("user:100", "score", "10") redis.hincrby("user:100", "score", 5) # => 15 redis.hincrbyfloat("user:100", "score", 2.5) # => "17.5" # Scan hash fields cursor, fields = redis.hscan("user:100", 0) # fields is a hash of field => value pairs redis.close ``` -------------------------------- ### Install Crystal Redis Shard Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/index.html This snippet shows how to add the crystal-redis gem to your project's shard.yml file and install it using the 'shards install' command. ```yaml dependencies: redis: github: stefanwille/crystal-redis version: ~> 2.6.0 ``` -------------------------------- ### Execute Basic Redis Key-Value Operations Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis.html Examples of common Redis commands such as GET, SET, and DEL implemented in Crystal. These methods allow for standard data manipulation within a Redis instance. ```crystal redis = Redis.new redis.set("key", "value") value = redis.get("key") redis.del("key") ``` -------------------------------- ### Crystal Redis Client Installation Source: https://github.com/stefanwille/crystal-redis/blob/master/README.md Add the crystal-redis gem to your project's shard.yml file to manage dependencies. After updating shard.yml, run 'shards install' to fetch the library. ```crystal dependencies: redis: github: stefanwille/crystal-redis ``` ```bash $ shards install ``` -------------------------------- ### Crystal Redis Client Installation on MacOS X Source: https://github.com/stefanwille/crystal-redis/blob/master/README.md Instructions for installing OpenSSL on MacOS X and configuring the PKG_CONFIG_PATH environment variable to resolve linker errors when building with the Crystal Redis client. ```bash $ brew install openssl $ export PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig ``` -------------------------------- ### Install Redis Shard Command Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/index.html This command-line instruction is used to install the crystal-redis library into your Crystal project after adding it to shard.yml. ```bash $ shards install ``` -------------------------------- ### Initialize and Access Redis::Future Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Future.html Demonstrates the structure of the Redis::Future class, including its constructor and methods for getting or setting the future value. ```crystal class Redis::Future def initialize @value = nil end def value @value end def value=(new_value) @value = new_value end end ``` -------------------------------- ### Manage Redis Server and Database Source: https://context7.com/stefanwille/crystal-redis/llms.txt Provides examples for querying server information, testing connections, performing database maintenance, and inspecting key metadata. ```crystal require "redis" redis = Redis.new # Get server info info = redis.info puts info["redis_version"] # Test connection redis.ping # => "PONG" # Database operations redis.select(1) redis.flushdb # Key serialization redis.set("mykey", "myvalue") serialized = redis.dump("mykey") redis.restore("newkey", 0, serialized) # Object inspection redis.object_encoding("mykey") redis.close ``` -------------------------------- ### Crystal Redis Client Initialization and Usage Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis.html Demonstrates how to require the redis library, instantiate a Redis client, and execute basic commands like SET, GET, and INCR. It also highlights the need for separate Redis instances per thread/coroutine. ```crystal require "redis" redis = Redis.new redis.set("foo", "bar") redis.get("foo") redis.incr("visitors") ``` -------------------------------- ### Get Keys Matching Pattern (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns all keys that match a given pattern. This is useful for key discovery and management. ```crystal redis.keys(pattern) ``` -------------------------------- ### Redis ZSCAN Command Example (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Demonstrates how to use the ZSCAN command to retrieve elements from a sorted set in Redis. It allows for pattern matching and limiting the number of returned elements. This function is part of the crystal-redis library. ```crystal redis.zscan("myzset", 0, "foo*", 1024) ``` -------------------------------- ### Implement Publish/Subscribe Messaging Source: https://context7.com/stefanwille/crystal-redis/llms.txt Provides examples for both publishing messages to channels and subscribing to them, including handling subscription events and message processing. ```crystal require "redis" publisher = Redis.new publisher.publish("news", "Breaking news!") subscriber = Redis.new subscriber.subscribe("news") do |on| on.message do |channel, message| puts "Received on #{channel}: #{message}" end end ``` -------------------------------- ### Implement Pipelining for Throughput Source: https://context7.com/stefanwille/crystal-redis/llms.txt Shows how to batch multiple commands into a single request to improve performance. Includes examples of retrieving results as an array or using futures for individual command responses. ```crystal require "redis" redis = Redis.new results = redis.pipelined do |pipeline| pipeline.set("key1", "value1") pipeline.get("key1") end redis.pipelined do |pipeline| future1 = pipeline.get("key1") end redis.close ``` -------------------------------- ### Perform Redis Key and Set Operations in Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/PipelineApi.html Examples of common Redis commands implemented in the crystal-redis library. These methods allow for manipulating keys, sets, and performing atomic operations. ```crystal # Example of setting a key with expiration redis.set("my_key", "value", ex: 60) # Example of adding members to a set redis.sadd("my_set", ["member1", "member2"]) # Example of pushing values to a list redis.rpush("my_list", ["val1", "val2"]) # Example of subscribing to channels redis.subscribe("channel1", "channel2") do |sub| sub.on_message do |channel, message| puts "Received #{message} from #{channel}" end end ``` -------------------------------- ### Get All Hash Values (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves all values from a hash stored at a specified key. This command is useful for fetching all elements within a Redis hash. ```crystal redis.hvals(key) ``` -------------------------------- ### Redis TYPE Command (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the string representation of the type of the value stored at a key. The return value is a String indicating the type of the key, or 'none' if the key does not exist. An example demonstrates setting a string value and then checking its type. ```Crystal def type(key) # Returns the string representation of the type of the value stored at key. # Return value: String, the type of key, or none when key does not exist. # Example: # redis.set("foo", 3) # redis.type("foo") # => "string" end ``` -------------------------------- ### Example Usage of Redis Pipeline API Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/PipelineApi.html Demonstrates how to use the PipelineApi object within a block provided by the `redis.pipelined` method to execute multiple Redis commands efficiently. This method groups commands into a single network round trip. ```crystal redis.pipelined do |pipeline| pipeline.set("foo1", "first") pipeline.set("foo2", "second") end ``` -------------------------------- ### Initialize and Manage Redis Client Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Client.html Demonstrates how to instantiate a new Redis client and perform basic lifecycle operations like closing the connection. The client supports various configuration parameters including host, port, and timeouts. ```crystal require "redis" # Initialize a new client client = Redis::Client.new(host: "localhost", port: 6379) # Access the connection conn = client.connection # Close the client connection client.close ``` -------------------------------- ### Get List Range (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns a specified range of elements from a list stored at a key. Supports start and stop indices. ```crystal redis.lrange(key, from, to) ``` -------------------------------- ### Initialize Redis Client Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/TransactionApi.html Shows the constructor method for initializing a new Redis client instance with a specific strategy and optional namespace. ```crystal def self.new(strategy, namespace = "") ``` -------------------------------- ### Redis::Commands Instance Methods Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html This section details the instance methods available in the Redis::Commands module for interacting with Redis. ```APIDOC ## Redis::Commands Instance Methods ### Description Provides methods for executing a wide range of Redis commands directly. ### Methods - **#append**(key, value) - **Description**: If key already exists and is a string, this command appends the value at the end of the string. - **Method**: POST (or relevant method based on Redis command) - **Endpoint**: /redis/commands/append - **Parameters**: - **key** (String) - Required - The key to append to. - **value** (String) - Required - The value to append. - **#auth**(password) - **Description**: Request for authentication in a password-protected Redis server. - **Method**: POST - **Endpoint**: /redis/commands/auth - **Parameters**: - **password** (String) - Required - The password for authentication. - **#bitcount**(key, from = nil, to = nil) - **Description**: Count the number of set bits (population counting) in a string. - **Method**: GET - **Endpoint**: /redis/commands/bitcount - **Parameters**: - **key** (String) - Required - The key whose string value is to be counted. - **from** (Integer) - Optional - The starting offset for counting. - **to** (Integer) - Optional - The ending offset for counting. - **#bitop**(operation, key, *keys : String) - **Description**: Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key. - **Method**: POST - **Endpoint**: /redis/commands/bitop - **Parameters**: - **operation** (String) - Required - The bitwise operation (AND, OR, XOR, NOT). - **key** (String) - Required - The destination key to store the result. - **keys** (Array) - Required - The source keys to perform the operation on. - **#bitop**(operation, key, keys : Array(String)) - **Description**: Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key. - **Method**: POST - **Endpoint**: /redis/commands/bitop - **Parameters**: - **operation** (String) - Required - The bitwise operation (AND, OR, XOR, NOT). - **key** (String) - Required - The destination key to store the result. - **keys** (Array) - Required - The source keys to perform the operation on. - **#bitpos**(key, bit, start = nil, to = nil) - **Description**: Return the position of the first bit set to 1 or 0 in a string. - **Method**: GET - **Endpoint**: /redis/commands/bitpos - **Parameters**: - **key** (String) - Required - The key whose string value is to be searched. - **bit** (Integer) - Required - The bit to search for (0 or 1). - **start** (Integer) - Optional - The starting offset for the search. - **to** (Integer) - Optional - The ending offset for the search. - **#blpop**(keys, timeout_in_seconds) - **Description**: BLPOP is a blocking list pop primitive. It is the counterpart of LPOP because while LPOP is non-blocking, BLPOP blocks until one of the specified lists contains an element or the specified timeout is reached. - **Method**: POST - **Endpoint**: /redis/commands/blpop - **Parameters**: - **keys** (Array) - Required - The list keys to pop from. - **timeout_in_seconds** (Integer) - Required - The maximum time to block in seconds. - **#brpop**(keys, timeout_in_seconds) - **Description**: BRPOP is a blocking list pop primitive. It is the counterpart of RPOP because while RPOP is non-blocking, BRPOP blocks until one of the specified lists contains an element or the specified timeout is reached. - **Method**: POST - **Endpoint**: /redis/commands/brpop - **Parameters**: - **keys** (Array) - Required - The list keys to pop from. - **timeout_in_seconds** (Integer) - Required - The maximum time to block in seconds. - **#brpoplpush**(source, destination, timeout_in_seconds = nil) - **Description**: BRPOPLPUSH is the blocking variant of RPOPLPUSH. It pops an element from the last list and pushes it to the first list. If the timeout is reached, it returns nil. - **Method**: POST - **Endpoint**: /redis/commands/brpoplpush - **Parameters**: - **source** (String) - Required - The key of the list to pop from. - **destination** (String) - Required - The key of the list to push to. - **timeout_in_seconds** (Integer) - Optional - The maximum time to block in seconds. - **#decr**(key) - **Description**: Decrements the number stored at key by one. - **Method**: POST - **Endpoint**: /redis/commands/decr - **Parameters**: - **key** (String) - Required - The key to decrement. - **#decrby**(key, decrement) - **Description**: Decrements the number stored at key by decrement. - **Method**: POST - **Endpoint**: /redis/commands/decrby - **Parameters**: - **key** (String) - Required - The key to decrement. - **decrement** (Integer) - Required - The amount to decrement by. - **#del**(keys : Array) - **Description**: Removes the specified keys. - **Method**: DELETE - **Endpoint**: /redis/commands/del - **Parameters**: - **keys** (Array) - Required - An array of keys to remove. - **#del**(*keys) - **Description**: Removes the specified keys. - **Method**: DELETE - **Endpoint**: /redis/commands/del - **Parameters**: - **keys** (Array) - Required - A variable number of keys to remove. - **#dump**(key) - **Description**: Serialize the value stored at key in a Redis-specific format and return it to the user. - **Method**: GET - **Endpoint**: /redis/commands/dump - **Parameters**: - **key** (String) - Required - The key to serialize. - **#echo**(message) - **Description**: Returns the given message. - **Method**: POST - **Endpoint**: /redis/commands/echo - **Parameters**: - **message** (String) - Required - The message to echo. - **#eval**(script : String, keys = [] of RedisValue, args = [] of RedisValue) - **Description**: EVAL and EVALSHA are used to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0. - **Method**: POST - **Endpoint**: /redis/commands/eval - **Parameters**: - **script** (String) - Required - The Lua script to execute. - **keys** (Array) - Optional - An array of keys to be passed to the script. - **args** (Array) - Optional - An array of arguments to be passed to the script. - **#evalsha**(sha1, keys = [] of RedisValue, args = [] of RedisValue) - **Description**: EVAL and EVALSHA are used to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0. - **Method**: POST - **Endpoint**: /redis/commands/evalsha - **Parameters**: - **sha1** (String) - Required - The SHA1 hash of the Lua script to execute. - **keys** (Array) - Optional - An array of keys to be passed to the script. - **args** (Array) - Optional - An array of arguments to be passed to the script. - **#exists**(key) - **Description**: Returns if key exists. - **Method**: GET - **Endpoint**: /redis/commands/exists - **Parameters**: - **key** (String) - Required - The key to check for existence. - **#expire**(key, seconds) - **Description**: Set a timeout on key. - **Method**: POST - **Endpoint**: /redis/commands/expire - **Parameters**: - **key** (String) - Required - The key to set the timeout on. - **seconds** (Integer) - Required - The timeout in seconds. - **#expireat**(key, unix_date) - **Description**: Set a timeout on key at a specified Unix timestamp. - **Method**: POST - **Endpoint**: /redis/commands/expireat - **Parameters**: - **key** (String) - Required - The key to set the timeout on. - **unix_date** (Integer) - Required - The Unix timestamp when the key should expire. ``` -------------------------------- ### Initialize Redis Pooled Client in Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/PooledClient.html Demonstrates the instantiation of a pooled Redis client. This approach allows the application to maintain a set of reusable connections, reducing latency and overhead for frequent database operations. ```crystal require "redis" # Initialize a pooled client with default settings client = Redis::PooledClient.new(host: "localhost", port: 6379, pool_size: 5) # Usage example client.set("key", "value") puts client.get("key") ``` -------------------------------- ### Basic Redis Connection in Crystal Source: https://context7.com/stefanwille/crystal-redis/llms.txt Demonstrates various ways to establish a Redis client connection in Crystal, including default, custom host/port, URL, Unix socket, SSL/TLS, and with timeouts/reconnection settings. Includes connection testing and closing. ```crystal require "redis" # Default connection (localhost:6379) redis = Redis.new # Custom host, port, and database redis = Redis.new(host: "localhost", port: 6379, database: 1) # Connection via URL redis = Redis.new(url: "redis://:my-secret-pw@my.redis.com:6380/my-database") # Unix socket connection redis = Redis.new(unixsocket: "/tmp/redis.sock") # SSL/TLS connection redis = Redis.new(host: "secure.redis.com", port: 6380, ssl: true) # With timeouts and reconnection settings redis = Redis.new( host: "localhost", port: 6379, password: "secret", database: 0, connect_timeout: 5.seconds, command_timeout: 2.seconds, reconnect: true ) # Test connection redis.ping # => "PONG" # Close connection when done redis.close ``` -------------------------------- ### Get length of a Redis hash Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the total number of fields contained in the hash stored at the key. ```crystal def hlen(key) ``` -------------------------------- ### Get List Length (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the number of elements in a list stored at a key. Provides the size of the list. ```crystal redis.llen(key) ``` -------------------------------- ### Connection and Basic Commands Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Commands for checking connection status, setting keys with expiry, and publishing messages. ```APIDOC ## PING ### Description Checks if the Redis server is responsive. ### Method GET ### Endpoint /ping ### Response #### Success Response (200) - **response** (String) - Should return 'PONG'. #### Response Example ```json { "response": "PONG" } ``` ## PSETEX ### Description Sets a key's value and its expiration time in milliseconds. ### Method POST ### Endpoint /psetex ### Parameters #### Request Body - **key** (String) - Required - The key to set. - **expire_in_milis** (Int) - Required - The expiration time in milliseconds. - **value** (String) - Required - The value to set for the key. ### Request Example ```json { "key": "mykey", "expire_in_milis": 5000, "value": "myvalue" } ``` ### Response #### Success Response (200) - **status** (String) - Indicates success. #### Response Example ```json { "status": "OK" } ``` ## PUBLISH ### Description Posts a message to a specified channel. ### Method POST ### Endpoint /publish ### Parameters #### Request Body - **channel** (String) - Required - The channel to publish to. - **message** (String) - Required - The message to send. ### Request Example ```json { "channel": "news", "message": "Hello world!" } ``` ### Response #### Success Response (200) - **subscribers** (Int) - The number of clients that received the message. #### Response Example ```json { "subscribers": 1 } ``` ``` -------------------------------- ### Get string length with strlen Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the length of the string value stored at the specified key. Returns 0 if the key does not exist. ```crystal def strlen(key) ``` -------------------------------- ### Get Server Information (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves server information and statistics. An optional section parameter can filter the information returned. ```crystal redis.info(section : String? = nil) ``` -------------------------------- ### Crystal Redis Connection Opening Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis.html Shows how to open a Redis connection using the Redis.new constructor with various options such as host, port, password, and timeouts. It also includes the Redis.open class method for managing connections within a block. ```crystal # Using Redis.new redis = Redis.new(host: "localhost", port: 6379, password: "mypassword", connect_timeout: 5.seconds) # Using Redis.open with a block Redis.open(url: "redis://localhost:6379/0", password: "mypassword") do |redis| redis.set("key", "value") end ``` -------------------------------- ### Server Information and Key Management Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Commands to retrieve server information and manage keys. ```APIDOC ## GET /redis/info ### Description Retrieves general information and statistics about the Redis server. Optionally, a specific section can be requested. ### Method GET ### Endpoint /redis/info ### Parameters #### Query Parameters - **section** (String) - Optional - The specific section of information to retrieve (e.g., "server", "clients", "memory"). If omitted, all information is returned. ### Response #### Success Response (200) - **info** (Object) - A hash containing server information and statistics. #### Response Example ```json { "info": { "server": { "redis_version": "7.0.0", "uptime_in_seconds": "12345" }, "clients": { "connected_clients": "5" } } } ``` ## GET /redis/keys ### Description Returns all keys that match the specified pattern. ### Method GET ### Endpoint /redis/keys ### Parameters #### Query Parameters - **pattern** (String) - Required - The pattern to match keys against (e.g., "user:*", "*id"). ### Request Example ```json { "pattern": "callmemaybe" } ``` ### Response #### Success Response (200) - **keys** (Array) - An array of keys matching the pattern. #### Response Example ```json { "keys": ["key1", "key2"] } ``` ``` -------------------------------- ### Get Sorted Set Elements by Range (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves a range of elements from a sorted set. It can optionally return the scores associated with each element. ```crystal def zrange(key, start, stop, with_scores = false) # Returns the specified range of elements in the sorted set stored at key. # Options: # * with_scores - true to return the scores of the elements together with the elements. # Example: # redis.zrange("myzset", 0, -1, with_scores: true) # => ["one", "1", "uno", "1", "two", "2", "three", "3"] end ``` -------------------------------- ### Get Object Encoding (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the internal encoding of the value associated with a key. Helps understand how Redis stores the data. ```crystal redis.object_encoding(key) ``` -------------------------------- ### Get object reference count in Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves the number of references for the value associated with a specific key. Returns an integer representing the reference count. ```crystal def object_refcount(key) ``` -------------------------------- ### Get Object Reference Count (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the reference count of the value associated with the key. Indicates how many clients are referencing the object. ```crystal redis.object_refcount(key) ``` -------------------------------- ### Remove and Get First List Element (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Removes and returns the first element from a list stored at a key. Modifies the list in place. ```crystal redis.lpop(key) ``` -------------------------------- ### Initialize and use Redis::PooledClient in Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/PooledClient.html Demonstrates how to instantiate a pooled Redis client and perform concurrent operations across multiple fibers. The client manages a pool of connections, ensuring efficient resource usage when accessed by multiple concurrent tasks. ```crystal redis = Redis::PooledClient.new(host: "localhost", port: 6379, pool_size: 5) 10.times do |i| spawn do redis.set("foo#{i}", "bar") redis.get("foo#{i}") # => "bar" end end ``` -------------------------------- ### Get List Element by Index (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves the element at a specific index within a list stored at a key. Supports negative indexing. ```crystal redis.lindex(key, index) ``` -------------------------------- ### Pattern Subscription with Redis Source: https://context7.com/stefanwille/crystal-redis/llms.txt Demonstrates how to subscribe to Redis channels using glob-style patterns. It handles pattern subscription, message reception, and unsubscription events. ```crystal subscriber.psubscribe("news:*", "alert:*") do |on| on.psubscribe do |pattern, subscriptions| puts "Subscribed to pattern #{pattern}" end on.pmessage do |pattern, channel, message| puts "Pattern #{pattern} matched channel #{channel}: #{message}" end on.punsubscribe do |pattern, subscriptions| puts "Unsubscribed from pattern #{pattern}" end end publisher.close subscriber.close ``` -------------------------------- ### Get Object Idle Time (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the number of seconds since the object stored at the key was last accessed. Useful for memory management. ```crystal redis.object_idletime(key) ``` -------------------------------- ### Get Multiple Key Values (Crystal Redis) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves the values associated with multiple specified keys. Returns an array of values corresponding to the input keys. ```crystal redis.mget(keys : Array(String)) : Array(RedisValue) ``` ```crystal redis.mget(*keys) ``` -------------------------------- ### Manage Redis Database and Keys Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Basic commands for selecting a database index and performing key-value operations. Includes advanced SET options for expiration and conditional updates. ```crystal redis.select(0) redis.set("foo", "test", ex: 7) redis.setbit("mykey", 7, 1) redis.setex("foo", 3, "bar") ``` -------------------------------- ### Redis::Commands - String Operations Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/PipelineApi.html Provides methods for string manipulation in Redis, including appending, getting, setting, and bitwise operations. ```APIDOC ## Redis::Commands - String Operations ### Description Methods for interacting with Redis string data types. ### Methods - **append(key, value)** - Appends a value to a key. - **get(key)** - Retrieves the value associated with a key. - **getbit(key, index)** - Returns the bit value at the specified offset for a string key. - **getrange(key, start_index, end_index)** - Returns a slice of the string value of a key. - **getset(key, value)** - Atomically sets a key's value and returns its old value. - **set(key, value)** - Sets the string value of a key. - **setbit(key, index, value)** - Sets or clears the bit at the specified offset for a string key. - **setex(key, seconds, value)** - Sets the string value of a key and its expiration time in seconds. - **setnx(key, value)** - Sets the string value of a key only if the key does not exist. - **strlen(key)** - Returns the length of the string value of a key. ``` -------------------------------- ### Set Range in Redis with Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Overwrites a portion of a string stored at a specific key starting at a given offset. Returns the total length of the modified string. ```crystal redis.setrange("foo", 6, "Redis") ``` -------------------------------- ### Initialize Redis::SocketWrapper Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/SocketWrapper.html Constructors for Redis::SocketWrapper. The first accepts a raw socket (TCPSocket, UNIXSocket, or SSL Socket), while the second accepts a block for initialization. ```crystal def self.new(socket : TCPSocket | UNIXSocket | OpenSSL::SSL::Socket::Client) # ... implementation ... end ``` ```crystal def self.new(&) # ... implementation ... end ``` -------------------------------- ### Defining Redis Subscription Callbacks in Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Subscription.html This snippet demonstrates the method signatures for setting callbacks on a Redis::Subscription instance. These methods allow handling incoming messages, pattern-matched messages, and subscription lifecycle events like subscribe, unsubscribe, psubscribe, and punsubscribe. ```crystal subscription = Redis::Subscription.new # Set message callbacks subscription.message { |channel, message| puts "Received #{message} on #{channel}" } subscription.pmessage { |pattern, channel, message| puts "Pattern #{pattern} matched #{channel}: #{message}" } # Set lifecycle callbacks subscription.subscribe { |channel, count| puts "Subscribed to #{channel}" } subscription.unsubscribe { |channel, count| puts "Unsubscribed from #{channel}" } subscription.psubscribe { |pattern, count| puts "Subscribed to pattern #{pattern}" } subscription.punsubscribe { |pattern, count| puts "Unsubscribed from pattern #{pattern}" } ``` -------------------------------- ### Get Rank by Score (High to Low) (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the rank of a member in a sorted set, ordered by score from high to low. Returns nil if the member or key does not exist. ```Crystal def zrevrank(key, member) # Implementation details for getting rank by score (high to low) end ``` -------------------------------- ### Get Random Key (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves a random key from the currently selected Redis database. This command is useful for various administrative tasks or when needing to operate on an arbitrary key. ```crystal redis.randomkey ``` -------------------------------- ### Crystal Redis Client Basic Usage Source: https://github.com/stefanwille/crystal-redis/blob/master/README.md Require the 'redis' library and instantiate a new Redis client. You can then execute Redis commands directly on the client object. ```crystal require "redis" redis = Redis.new redis.set("foo", "bar") redis.get("foo") ``` -------------------------------- ### MSETNX: Conditionally set multiple Redis keys (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html The MSETNX command sets multiple keys to their values, but only if none of the keys already exist. If any key exists, no operation is performed. It returns 1 if all keys were set, and 0 otherwise. This is useful for ensuring that a set of keys is created atomically. ```crystal def msetnx(hash) ``` -------------------------------- ### Basic Redis Commands in Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/index.html This Crystal code snippet shows how to perform basic Redis operations like setting a key-value pair and retrieving its value using the connected Redis client. ```crystal redis.set("foo", "bar") redis.get("foo") ``` -------------------------------- ### Get Rank of Sorted Set Member (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the rank (position) of a member within a sorted set, based on ascending scores. Returns nil if the member or key does not exist. ```crystal def zrank(key, member) # Returns the rank of member in the sorted set stored at key, with the scores ordered from low to high. # Return value: # * If member exists in the sorted set, Integer: the rank of member. # * If member does not exist in the sorted set or key does not exist: nil. end ``` -------------------------------- ### Get Redis Server URL (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis.html Retrieves the server URL associated with the current Redis client instance. This can be useful for configuration or debugging purposes. ```Crystal redis.url ``` -------------------------------- ### Manage Redis Sets with Crystal Source: https://context7.com/stefanwille/crystal-redis/llms.txt Illustrates how to work with Redis sets (unordered collections of unique elements) using the Crystal Redis client. Includes adding/removing members, checking membership, and performing set operations. ```crystal require "redis" redis = Redis.new redis.del("myset", "otherset") # Add members redis.sadd("myset", "a", "b", "c") redis.sadd("myset", ["d", "e"]) # Add from array # Get all members redis.smembers("myset") # => ["a", "b", "c", "d", "e"] # Check membership redis.sismember("myset", "a") # => 1 redis.sismember("myset", "z") # => 0 # Get set size redis.scard("myset") # => 5 # Remove members redis.srem("myset", "a") redis.srem("myset", ["b", "c"]) # Pop random member(s) redis.spop("myset") # => random member (removed) redis.spop("myset", 2) # => array of 2 random members (removed) # Get random member(s) without removing redis.srandmember("myset") # => random member redis.srandmember("myset", 2) # => array of 2 random members redis.srandmember("myset", -2) # May return duplicates # Move member between sets redis.sadd("set1", "x") redis.smove("set1", "set2", "x") # Set operations redis.sadd("setA", "1", "2", "3") redis.sadd("setB", "2", "3", "4") # Union redis.sunion("setA", "setB") # => ["1", "2", "3", "4"] redis.sunionstore("result", "setA", "setB") # Store result redis.close ``` -------------------------------- ### Multiple Key Commands Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Commands for operating on multiple keys simultaneously. ```APIDOC ## MGET ### Description Retrieves the values of multiple specified keys. ### Method GET (conceptual) ### Endpoint /redis/mget ### Parameters #### Path Parameters None #### Query Parameters - **keys** (Array) - Required - An array of keys to retrieve values for. ### Request Example ``` GET /redis/mget?keys[]=foo1&keys[]=foo2 ``` ### Response #### Success Response (200) - **return_value** (Array) - An array of values corresponding to the provided keys. Nil is returned for non-existent keys or keys not holding string values. #### Response Example ```json { "return_value": ["test1", "test2"] } ``` ``` ```APIDOC ## MSET ### Description Sets multiple keys to their respective values. ### Method POST (conceptual) ### Endpoint /redis/mset ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **hash** (Hash) - Required - A hash where keys are the Redis keys and values are the values to set. ### Request Example ```json { "hash": { "foo1": "bar1", "foo2": "bar2" } } ``` ### Response #### Success Response (200) - **return_value** (String) - "OK" #### Response Example ```json { "return_value": "OK" } ``` ``` ```APIDOC ## MSETNX ### Description Sets multiple keys to their respective values only if none of the keys already exist. ### Method POST (conceptual) ### Endpoint /redis/msetnx ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **hash** (Hash) - Required - A hash where keys are the Redis keys and values are the values to set. ### Request Example ```json { "hash": { "key1": "hello", "key2": "there" } } ``` ### Response #### Success Response (200) - **return_value** (Integer) - 1 if all keys were set, 0 if no keys were set (because at least one key already existed). #### Response Example ```json { "return_value": 1 } ``` ``` -------------------------------- ### Get Set Cardinality (Redis SCARD - Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the number of elements (cardinality) in a set stored at a specified key. This is a quick way to determine the size of a set without retrieving all its members. ```crystal def scard(key) # ... implementation details ... end ``` -------------------------------- ### Redis Echo Command Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the given message. ```APIDOC ## ECHO /echo ### Description Returns the given message. ### Method POST ### Endpoint /echo ### Parameters #### Request Body - **message** (string) - Required - The message to be echoed. ### Request Example ```json { "message": "Hello Redis" } ``` ### Response #### Success Response (200) - **echoed_message** (string) - The message that was echoed. ``` -------------------------------- ### Set PKG_CONFIG_PATH for OpenSSL on macOS Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/index.html This command sets the PKG_CONFIG_PATH environment variable to help Crystal locate OpenSSL development files on macOS, often required for installation. ```bash export PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig ``` -------------------------------- ### Redis String Operations Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Basic operations for retrieving and manipulating string values in Redis. This includes getting values by key, accessing bits within strings, extracting substrings, and atomic get-and-set operations. ```crystal redis.get(key) redis.getbit(key, index) redis.getrange(key, start_index, end_index) redis.getset(key, value) ``` -------------------------------- ### Configure Redis Strategy Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Client.html Shows how to retrieve and update the execution strategy for the Redis client. The strategy determines how commands are dispatched to the Redis server. ```crystal require "redis" client = Redis::Client.new # Get current strategy current_strategy = client.strategy # Set a new strategy # client.strategy = new_strategy ``` -------------------------------- ### Connect to Redis using Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis.html Establishes a connection to a Redis server. Supports various connection options including host, port, Unix domain sockets, password, database selection, SSL, and timeouts. It can also connect using a Redis URL, which overrides other connection parameters. ```crystal redis = Redis.new redis.incr("counter") redis.close ``` ```crystal redis = Redis.new(host: "localhost", port: 6379) ... ``` ```crystal redis = Redis.new(unixsocket: "/tmp/redis.sock") ... ``` ```crystal redis = Redis.new(url: "redis://:my-secret-pw@my.redis.com:6380/my-database") ... ``` -------------------------------- ### Get Sorted Set Elements by Score Range (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Retrieves elements from a sorted set that fall within a specified score range (inclusive). It supports optional limits for pagination and an option to include scores. ```crystal def zrangebyscore(key, min, max, limit = nil, with_scores = false) # Returns all the elements in the sorted set at key with a score between max and min (including elements with score equal to max or min). # Options: # * limit - an array of [offset, count]. Skip offset members, return a maximum of count members. # * with_scores - true to return the scores of the elements together with the elements. end ``` -------------------------------- ### Get Sorted Set Element Count by Lexicographical Range (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the number of elements in a sorted set within a specified lexicographical range. This is useful when elements are inserted with the same score to enforce lexicographical ordering. ```crystal def zlexcount(key, min, max) # When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns the number of elements in the sorted set at key with a value between min and max. end ``` -------------------------------- ### Key Management Commands Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Commands for managing keys, including random key retrieval, renaming, and restoring. ```APIDOC ## QUIT ### Description Asks the server to close the connection. ### Method POST ### Endpoint /quit ### Response #### Success Response (200) - **message** (String) - Confirmation message. #### Response Example ```json { "message": "Connection closed." } ``` ## RANDOMKEY ### Description Returns a random key from the currently selected database. ### Method GET ### Endpoint /randomkey ### Response #### Success Response (200) - **key** (String) - A random key from the database. #### Response Example ```json { "key": "some_random_key" } ``` ## RENAME ### Description Renames a key from `old_key` to `new_key`. ### Method POST ### Endpoint /rename ### Parameters #### Request Body - **old_key** (String) - Required - The current name of the key. - **new_key** (String) - Required - The new name for the key. ### Request Example ```json { "old_key": "oldname", "new_key": "newname" } ``` ### Response #### Success Response (200) - **status** (String) - Indicates success. #### Response Example ```json { "status": "OK" } ``` ## RENAMENX ### Description Renames a key from `old_key` to `new_key` only if `new_key` does not already exist. ### Method POST ### Endpoint /renamenx ### Parameters #### Request Body - **old_key** (String) - Required - The current name of the key. - **new_key** (String) - Required - The new name for the key. ### Request Example ```json { "old_key": "oldname", "new_key": "newname" } ``` ### Response #### Success Response (200) - **status** (String) - Indicates success or failure (if new_key exists). #### Response Example ```json { "status": "OK" } ``` ## RESTORE ### Description Creates a key associated with a value obtained by deserializing the provided serialized value (obtained via DUMP). ### Method POST ### Endpoint /restore ### Parameters #### Request Body - **key** (String) - Required - The key to restore. - **ttl_in_milis** (Int) - Required - The time to live in milliseconds. - **serialized_value** (String) - Required - The serialized value. - **replace** (Boolean) - Optional - Whether to replace the key if it already exists (default: false). ### Request Example ```json { "key": "mykey", "ttl_in_milis": 10000, "serialized_value": "some_serialized_data", "replace": true } ``` ### Response #### Success Response (200) - **status** (String) - Indicates success. #### Response Example ```json { "status": "OK" } ``` ``` -------------------------------- ### Get Sorted Set Element Count by Score Range (Crystal) Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/Redis/Commands.html Returns the number of elements in a sorted set within a specified score range. It takes the key, minimum score, and maximum score as input. ```crystal def zcount(key, min, max) # Returns the number of elements in the sorted set at key with a score between min and max. end ``` -------------------------------- ### Require and Connect to Redis in Crystal Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/index.html This Crystal code demonstrates how to require the redis library and establish a connection to a Redis server using Redis.new. ```crystal require "redis" redis = Redis.new ``` -------------------------------- ### Configure Redis Unix Socket for Development Source: https://github.com/stefanwille/crystal-redis/blob/master/docs/index.html Instructions for enabling Unix domain socket support in the redis.conf file to allow the test suite to run correctly. ```text unixsocket /tmp/redis.sock ```