Created
August 24, 2023 01:21
-
-
Save bennettblack/4f8cd2d772cbd14dd122d084121fe557 to your computer and use it in GitHub Desktop.
Get all Redis keys in a connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services; | |
use Illuminate\Support\Facades\Redis; | |
class RedisService | |
{ | |
public static function getValues(string $connection) | |
{ | |
$keys = RedisService::getKeys('active_streams_connection'); | |
if($keys){ | |
// Laravel will serialize everything from mget. | |
$result = Redis::connection($connection)->mget($keys); | |
$values = array_map('unserialize', $result); | |
}else{ | |
$values = []; | |
} | |
return $values; | |
} | |
public static function getKeys(string $connection): array | |
{ | |
$keys = []; | |
// Set the cursor to start at 0 (initial value) | |
// The first value [0] returned by SCAN is the cursor to use for the next iteration. | |
// When redis returns a 0 again for the cursor, it means there are no more keys to return. | |
$cursor = '0'; | |
// Using a custom connection | |
$redis = Redis::connection($connection); | |
// Use a loop to retrieve all keys from the cache | |
do { | |
// Match everything. Returns false if no matches. | |
$result = $redis->scan($cursor, 'match', '*'); | |
if($result){ | |
// Update cursor | |
$cursor = $result[0]; | |
$keys = [...$keys, ...$result[1]]; | |
}else{ | |
$cursor = 0; | |
} | |
} while ($cursor); // when it's zero again, it'll be a loose false. | |
return $keys; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment