### Basic Redis Operations with Redis::Cluster::Fast Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Illustrates fundamental Redis operations using the Redis::Cluster::Fast client, including SET, GET, MSET, MGET, HSET, and HGETALL. It shows how to retrieve values as scalars, array references, arrays, hash references, and hashes. ```perl $redis->set('test', 123); # '123' my $str = $redis->get('test'); $redis->mset('{my}foo', 'hoge', '{my}bar', 'fuga'); # get as array-ref my $array_ref = $redis->mget('{my}foo', '{my}bar'); # get as array my @array = $redis->mget('{my}foo', '{my}bar'); $redis->hset('mymap', 'field1', 'Hello'); $redis->hset('mymap', 'field2', 'ByeBye'); # get as hash-ref my $hash_ref = { $redis->hgetall('mymap') }; # get as hash my %hash = $redis->hgetall('mymap'); ``` -------------------------------- ### Redis Batched Pipeline Operations in Perl Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Optimizes throughput by batching Redis commands for pipelined execution using Redis::Cluster::Fast. This example demonstrates queuing a large number of commands, processing them in batches via `run_event_loop()`, and then verifying results. It includes performance measurement to quantify the efficiency gains. ```perl use Time::HiRes qw/gettimeofday tv_interval/; use Redis::Cluster::Fast; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000', 'localhost:7001', 'localhost:7002'], command_timeout => 0.05, ); my $batch_size = 100; my $total_commands = 10000; my $command_count = 0; my $start_time = [gettimeofday]; # Queue commands in batches for my $i (1 .. $total_commands) { $redis->set("key:$i", "value:$i", sub { my ($result, $error) = @_; die "Error: $error" if $error; }); $command_count++; # Process batch every 100 commands if ($command_count % $batch_size == 0) { $redis->run_event_loop(); # Send and start receiving responses } } # Wait for all remaining callbacks to complete $redis->wait_all_responses(); my $elapsed = tv_interval($start_time); printf "Processed %d commands in %.3f seconds (%.0f ops/sec)\n", $total_commands, $elapsed, $total_commands / $elapsed; # Verify with batched GET operations my @retrieved_values; for my $i (1 .. 100) { $redis->get("key:$i", sub { my ($result, $error) = @_; push @retrieved_values, $result unless $error; }); $redis->run_event_loop() if $i % $batch_size == 0; } $redis->wait_all_responses(); print "Retrieved ", scalar(@retrieved_values), " values\n"; ``` -------------------------------- ### Redis Sorted Set Operations in Perl Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Demonstrates operations on Redis sorted sets, including adding members with scores, retrieving members by rank (ascending and descending), getting a member's score, incrementing scores, getting a member's rank, getting the cardinality, and removing members. This is useful for implementing features like leaderboards. ```perl use Redis::Cluster::Fast; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000', 'localhost:7001'], command_timeout => 1.0, ); # ZADD - add members with scores $redis->zadd('leaderboard', 100, 'player1'); $redis->zadd('leaderboard', 250, 'player2'); $redis->zadd('leaderboard', 175, 'player3'); # ZRANGE - get range by rank (ascending) my $top_players = $redis->zrange('leaderboard', 0, 1); # Returns: ['player1', 'player3'] (lowest scores first) # ZREVRANGE - get range by rank (descending) my $leaders = $redis->zrevrange('leaderboard', 0, 1, 'WITHSCORES'); # Returns: ['player2', '250', 'player3', '175'] # ZSCORE - get member score my $score = $redis->zscore('leaderboard', 'player2'); # Returns: '250' # ZINCRBY - increment member score $redis->zincrby('leaderboard', 50, 'player1'); my $new_score = $redis->zscore('leaderboard', 'player1'); # Returns: '150' # ZRANK - get member rank (0-based, ascending) my $rank = $redis->zrank('leaderboard', 'player1'); # Returns: 0 (lowest score) # ZCARD - get sorted set cardinality my $player_count = $redis->zcard('leaderboard'); # Returns: 3 # ZREM - remove members $redis->zrem('leaderboard', 'player1'); ``` -------------------------------- ### Execute Redis String Commands with Cluster Routing Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Perform SET, GET, MSET, MGET, and INCR operations on Redis Cluster with automatic key slot routing. Supports expiration via EX parameter, multiple operations using hash tags for same-slot keys, and both scalar and list context returns for multi-get operations. ```perl # SET command - store a value $redis->set('user:1000', 'John Doe'); # GET command - retrieve a value my $name = $redis->get('user:1000'); # SET with expiration (EX = seconds) $redis->set('session:abc123', 'session_data', 'EX', 300); # Multiple SET operations using hash tags for same slot $redis->mset('{user:1000}name', 'John', '{user:1000}email', 'john@example.com'); # Multiple GET operations - returns array reference in scalar context my $values = $redis->mget('{user:1000}name', '{user:1000}email'); # Multiple GET operations - returns array in list context my @values = $redis->mget('{user:1000}name', '{user:1000}email'); # INCR command for counters $redis->set('page:views', 0); $redis->incr('page:views'); $redis->incr('page:views'); my $views = $redis->get('page:views'); ``` -------------------------------- ### Manipulate Redis List Operations for Queues and Stacks Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Execute LPUSH, RPUSH, LPOP, RPOP, LRANGE, and LLEN operations on Redis Cluster lists. Supports pushing and popping from both ends, retrieving ranges of elements, and getting list length for queue and stack implementations. ```perl # LPUSH - push elements to list head $redis->lpush('queue:tasks', 'task1'); $redis->lpush('queue:tasks', 'task2', 'task3'); # RPUSH - push elements to list tail $redis->rpush('queue:notifications', 'notification1', 'notification2'); # LPOP - pop element from list head my $task = $redis->lpop('queue:tasks'); # RPOP - pop element from list tail my $notification = $redis->rpop('queue:notifications'); # LRANGE - get range of elements $redis->rpush('items', 'item1', 'item2', 'item3', 'item4', 'item5'); my $items = $redis->lrange('items', 0, 2); # LLEN - get list length my $length = $redis->llen('items'); ``` -------------------------------- ### Redis Set Operations in Perl Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Performs basic set operations like adding members, retrieving members, checking membership, getting cardinality, and removing members using Redis::Cluster::Fast. It also shows set intersection and union operations, utilizing hash tags for commands that need to operate on keys within the same slot. ```perl use Redis::Cluster::Fast; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000', 'localhost:7001'], command_timeout => 1.0, ); # SADD - add members to set $redis->sadd('tags:article:100', 'perl', 'redis', 'database'); # SMEMBERS - get all set members my $tags = $redis->smembers('tags:article:100'); # Returns: ['perl', 'redis', 'database'] (order not guaranteed) # SISMEMBER - check membership my $is_member = $redis->sismember('tags:article:100', 'perl'); # Returns: 1 (true) # SCARD - get set cardinality my $tag_count = $redis->scard('tags:article:100'); # Returns: 3 # Set operations with hash tags for same slot $redis->sadd('{article:100}tags:post1', 'perl', 'programming'); $redis->sadd('{article:100}tags:post2', 'redis', 'programming'); # SINTER - intersection my $common_tags = $redis->sinter('{article:100}tags:post1', '{article:100}tags:post2'); # Returns: ['programming'] # SUNION - union my $all_tags = $redis->sunion('{article:100}tags:post1', '{article:100}tags:post2'); # Returns: ['perl', 'programming', 'redis'] # SREM - remove members $redis->srem('tags:article:100', 'database'); ``` -------------------------------- ### Initialize Redis::Cluster::Fast Client Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Demonstrates how to create a new instance of the Redis::Cluster::Fast client. It shows the required 'startup_nodes' argument and optional parameters like 'connect_timeout', 'command_timeout', and 'max_retry_count'. ```perl use Redis::Cluster::Fast; Redis::Cluster::Fast::srandom(100); my $redis = Redis::Cluster::Fast->new( startup_nodes => [ 'localhost:9000', 'localhost:9001', 'localhost:9002', 'localhost:9003', 'localhost:9004', 'localhost:9005', ], connect_timeout => 0.05, command_timeout => 0.05, max_retry_count => 10, ); ``` -------------------------------- ### Initialize Redis Cluster Client with Connection Parameters Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Create and configure a new Redis::Cluster::Fast client instance with startup nodes and timeout settings. The client automatically discovers cluster topology and handles MOVED, ASK, TRYAGAIN, and CLUSTERDOWN errors with configurable retry logic. Returns a ready-to-use Redis Cluster client object. ```perl use Redis::Cluster::Fast; # Set random seed for cluster node selection (optional) Redis::Cluster::Fast::srandom(100); # Initialize client with cluster nodes my $redis = Redis::Cluster::Fast->new( startup_nodes => [ 'localhost:9000', 'localhost:9001', 'localhost:9002', 'localhost:9003', 'localhost:9004', 'localhost:9005', ], connect_timeout => 0.05, command_timeout => 0.05, max_retry_count => 10, cluster_discovery_retry_timeout => 1.0, route_use_slots => 0, ); # Client is now ready to execute commands my $result = $redis->ping(); ``` -------------------------------- ### Connect to Redis (Perl) Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Connects to the Redis server. Manual calls are generally not recommended. If fork() is to be used, connect should be called after fork(). ```Perl my $redis = Redis::Fast->new(); ``` -------------------------------- ### Redis Asynchronous Pipeline Commands in Perl Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Illustrates how to use pipeline mode for asynchronous command execution with callbacks in Redis::Cluster::Fast. This method queues commands and executes them in batches, allowing for non-blocking operations and handling responses via provided subroutines. It is suitable for improving application responsiveness. ```perl use Redis::Cluster::Fast; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000', 'localhost:7001'], command_timeout => 1.0, ); # Queue commands with callbacks (non-blocking) my $get_result; my $get_error; $redis->get('key1', sub { my ($result, $error) = @_; if ($error) { warn "GET error: $error"; } else { print "key1 = $result\n"; } }); $redis->set('key2', 'value2', sub { my ($result, $error) = @_; if ($error) { warn "SET error: $error"; } else { print "SET successful: $result\n"; } }); $redis->hgetall('user:1000', sub { my ($result, $error) = @_; if ($error) { warn "HGETALL error: $error"; } else { my %hash = @$result; # $result is array ref for HGETALL print "User data: ", join(", ", %hash), "\n"; } }); # Send all queued commands and wait for all responses $redis->wait_all_responses(); # Alternative: wait for at least one response # $redis->wait_one_response(); # Alternative: non-blocking send/receive # $redis->run_event_loop(); # Send commands, process available responses, don't wait ``` -------------------------------- ### Execute Redis Command with Arguments (Perl) Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Executes a Redis command with provided arguments. Commands can be specified directly or by concatenating subcommands with underscores (e.g., 'cluster_info'). This method does not support Pub/Sub commands. It is recommended to call 'disconnect' before issuing fork() after this command. ```Perl my $result = $redis->command(@args); ``` -------------------------------- ### Configuring Random Seed with srandom Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Explains the use of the `srandom` method in Redis::Cluster::Fast, which is based on hiredis-cluster's random node selection for topology requests. The `$seed` argument is an unsigned integer used to seed the random number generator. ```perl Redis::Cluster::Fast::srandom(100); ``` -------------------------------- ### Execute Redis Cluster Commands (Perl) Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Run Redis Cluster-specific commands like CLUSTER INFO, CLUSTER NODES, and CLUSTER SLOTS for cluster management and monitoring. Subcommands can be accessed using underscore notation. Requires a connected Redis::Cluster::Fast object. ```perl use Redis::Cluster::Fast; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000'] ); # CLUSTER INFO - get cluster state information my $cluster_info = $redis->cluster_info(); print $cluster_info; # CLUSTER NODES - get cluster topology my $nodes = $redis->cluster_nodes(); print $nodes; # Command with subcommands using underscore notation my $keyslot = $redis->cluster_keyslot('mykey'); print "Keyslot for 'mykey': $keyslot\n"; # CLUSTER SLOTS (when route_use_slots is enabled) my $redis_with_slots = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000'], route_use_slots => 1, ); my $slots_info = $redis_with_slots->cluster_slots(); print "Cluster Slots Info:\n", $slots_info, "\n"; ``` -------------------------------- ### Execute Redis Command in Pipeline with Callback (Perl) Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Runs a Redis command in pipeline mode with arguments and a callback function. Commands in a pipeline are sent and received together and are not sent to Redis until 'run_event_loop', 'wait_one_response', or 'wait_all_responses' is called. The callback receives the command result and any error message. Client methods cannot be called within the callback. Avoid fork() after this command without disconnecting if callbacks are incomplete. ```Perl $redis->get('test', sub { my ($result, $error) = @_; # some operations... }); ``` -------------------------------- ### Run Event Loop for Non-blocking Operations (Perl) Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md A non-blocking method that allows issuing commands without waiting for responses. It sends any unsent commands in the pipeline and executes callbacks for received responses. Timeouts propagate errors to corresponding callbacks. Returns 1 on success, 0 if no callbacks remain, or undef on error. Recommended for asynchronous command execution. ```Perl # Queue multiple commands in pipeline mode $redis->set('key1', 'value1', sub {}); $redis->get('key2', sub {}); # Send commands to Redis without waiting for responses $redis->run_event_loop(); # If any responses are available, read them immediately without waiting for the rest $redis->run_event_loop(); ``` -------------------------------- ### Perform Redis Hash Operations for Structured Data Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Execute HSET, HGET, HMSET, HGETALL, HDEL, HEXISTS, and HLEN operations on Redis Cluster hash data structures. Supports single and multiple field operations, scalar and list context returns for HGETALL, and field existence checks. ```perl # HSET - set hash field $redis->hset('user:2000', 'name', 'Alice'); $redis->hset('user:2000', 'email', 'alice@example.com'); $redis->hset('user:2000', 'age', 30); # HGET - get single hash field my $email = $redis->hget('user:2000', 'email'); # HMSET - set multiple hash fields at once $redis->hmset('user:3000', 'name', 'Bob', 'email', 'bob@example.com', 'country', 'USA' ); # HGETALL - get all fields and values as hash in list context my %user = $redis->hgetall('user:2000'); # HGETALL - get as hash reference in scalar context my $user_ref = { $redis->hgetall('user:3000') }; # HDEL - delete hash fields $redis->hdel('user:2000', 'age'); # HEXISTS - check if field exists my $exists = $redis->hexists('user:2000', 'name'); # HLEN - get number of fields my $field_count = $redis->hlen('user:2000'); ``` -------------------------------- ### Control Redis Cluster Async Event Loop (Perl) Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Gain fine-grained control over asynchronous command execution using event loop methods like run_event_loop() and wait_one_response(). This allows for efficient handling of multiple concurrent Redis operations and timeouts. ```perl use Redis::Cluster::Fast; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000', 'localhost:7001'], command_timeout => 0.5, ); my $responses_received = 0; # Queue multiple commands for my $i (1..10) { $redis->get("key:$i", sub { my ($result, $error) = @_; $responses_received++; print "Response $responses_received: ", ($error || $result), "\n"; }); } # Non-blocking: send commands and process available responses my $status = $redis->run_event_loop(); print "Status after run_event_loop: $status\n"; # Check if responses are available without blocking while ($redis->run_event_loop()) { print "Processed some responses...\n"; last if $responses_received >= 5; # Process first 5 } # Wait for at least one more response (blocking) $status = $redis->wait_one_response(); print "Received one response, status: $status\n"; # Wait for all remaining responses (blocking) $status = $redis->wait_all_responses(); print "All responses received, status: $status\n"; # Example with timeout handling $redis->set('test_key', 'test_value', sub { my ($result, $error) = @_; if ($error) { if ($error =~ /timeout/i) { warn "Command timed out: $error"; } else { warn "Redis error: $error"; } } }); $redis->wait_all_responses(); ``` -------------------------------- ### Manage Redis Cluster Connections with Fork (Perl) Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Explicitly manage Redis connections, especially around fork() operations. Disconnect before forking and reconnect in child and parent processes to ensure proper connection handling. This prevents issues with shared file descriptors. ```perl use Redis::Cluster::Fast; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000', 'localhost:7001'] ); # Normal operations $redis->set('key1', 'value1'); # Disconnect before fork (important!) $redis->disconnect(); my $pid = fork(); if ($pid == 0) { # Child process - reconnect after fork $redis->connect(); $redis->set('child_key', 'child_value'); my $value = $redis->get('child_key'); print "Child got: $value\n"; exit(0); } else { # Parent process - reconnect after fork $redis->connect(); $redis->set('parent_key', 'parent_value'); my $value = $redis->get('parent_key'); print "Parent got: $value\n"; waitpid($pid, 0); } # disconnect() will wait for all pending callbacks before disconnecting $redis->set('final_key', 'final', sub { my ($result, $error) = @_; print "Final command completed\n"; }); $redis->disconnect(); # Blocks until callback executes ``` -------------------------------- ### Wait for All Responses (Perl) Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Blocks execution until all unexecuted callbacks are completed. This ensures all pending asynchronous operations are finished before proceeding. Returns 1 on success, 0 if no callbacks remain, or undef on error. ```Perl my $status = $redis->wait_all_responses(); ``` -------------------------------- ### Wait for One Response (Perl) Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Blocks execution until at least one unexecuted callback is executed. Useful for synchronous-like behavior when a response is needed. Returns 1 on success, 0 if no callbacks remain, or undef on error. ```Perl my $status = $redis->wait_one_response(); ``` -------------------------------- ### Disconnect from Redis (Perl) Source: https://github.com/plainbanana/redis-cluster-fast/blob/master/README.md Disconnects from the Redis server after ensuring all pending commands are executed. Manual calls are generally not recommended. If fork() is to be used, disconnect should be called before fork(). ```Perl $redis->disconnect(); ``` -------------------------------- ### Handle Redis Cluster Errors and Timeouts (Perl) Source: https://context7.com/plainbanana/redis-cluster-fast/llms.txt Implement robust error handling for Redis cluster operations, including synchronous and asynchronous error callbacks. The module supports automatic retries for specific errors like MOVED, ASK, TRYAGAIN, and CLUSTERDOWN. ```perl use Redis::Cluster::Fast; use Try::Tiny; my $redis = Redis::Cluster::Fast->new( startup_nodes => ['localhost:7000', 'localhost:7001', 'localhost:7002'], connect_timeout => 0.5, command_timeout => 1.0, max_retry_count => 5, # Automatically retry on MOVED, ASK, TRYAGAIN, CLUSTERDOWN ); # Synchronous error handling with eval eval { my $result = $redis->get('mykey'); }; if ($@) { print "Error occurred: $@\n"; # Error format: "[command] error message" } # Asynchronous error handling in callbacks $redis->get('another_key', sub { my ($result, $error) = @_; if ($error) { # $error contains either Redis error or client error (e.g., "Timeout") print "Error: $error\n"; return; } # $result is undef for non-existent keys if (defined $result) { print "Value: $result\n"; } else { print "Key not found\n"; } }); $redis->wait_all_responses(); # Handle connection errors during initialization try { my $redis_bad = Redis::Cluster::Fast->new( startup_nodes => ['nonexistent:7000'], connect_timeout => 0.1, ); } catch { print "Failed to connect: $_"; }; # Cluster-specific errors are automatically retried: # - MOVED: key moved to different slot ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.