Last active
November 21, 2022 11:11
-
-
Save jcefoli/1f35cb87b333c427bcf6 to your computer and use it in GitHub Desktop.
List All Key/Value Pairs in Redis using the Predis Library. Assumes that Redis is running locally on default port 6379 with no password auth
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
<? | |
//Include Predis library. See https://github.com/nrk/predis for more info | |
require "Predis/Autoloader.php"; | |
//Connect to Redis | |
Predis\Autoloader::register(); | |
try { | |
$redis = new Predis\Client(); | |
$redis = new Predis\Client(array( | |
"scheme" => "tcp", | |
"host" => "127.0.0.1")) | |
; | |
} | |
catch (Exception $e) { | |
echo "Couldn't connect to Redis"; | |
echo $e->getMessage(); | |
} | |
//Get list of all keys. This creates an array of keys from the redis-cli output of "KEYS *" | |
$list = $redis->keys("*"); | |
//Optional: Sort Keys alphabetically | |
sort($list); | |
//Loop through list of keys | |
foreach ($list as $key) | |
{ | |
//Get Value of Key from Redis | |
$value = $redis->get($key); | |
//Print Key/value Pairs | |
echo "<b>Key:</b> $key <br /><b>Value:</b> $value <br /><br />"; | |
} | |
//Disconnect from Redis | |
$redis->disconnect(); | |
?> |
While this works and is a correct solution,
just keep in mind that some cloud Redis options do not support the "key *" command - as it is very expensive.
A workaround to this is described here:
- https://stackoverflow.com/questions/28545549/how-to-use-scan-with-the-match-option-in-predis
- https://csil-git1.cs.surrey.sfu.ca/djh10/group1/blob/master/vendor/predis/predis/examples/RedisCollectionsIterators.php
use Predis\Collection\Iterator;
$client = ...;
$pattern = 'foo*';
foreach (new Iterator\Keyspace($client, $pattern) as $key) {
...
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks, it's works)