Skip to content

Instantly share code, notes, and snippets.

@Ulv
Last active January 3, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ulv/9a3385dbb24ce750ab46989c15f85176 to your computer and use it in GitHub Desktop.
Save Ulv/9a3385dbb24ce750ab46989c15f85176 to your computer and use it in GitHub Desktop.
Function to apply callback to multiple keys defined by pattern.fastKeysCallback() uses redis SCAN with 100 elements
$redis = new Redis();
$redis->pconnect('127.0.0.1', 33379);
/**
* @param $redis
* @param string $mask
* @param $callback
*
* @return array|bool
*/
function fastKeysCallback($redis, $mask = '*', $callback) {
if (!($redis instanceof Redis)) {
return false;
} elseif (!is_callable($callback)) {
return false;
}
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$it = null;
while ($arr_keys = $redis->scan($it, $mask, 100)) {
foreach ($arr_keys as $str_key) {
call_user_func($callback, $str_key);
}
usleep(10000);
}
return true;
}
$result = fastKeysCallback($redis, '/sets/*', function($key) use ($redis) {
if ($redis->ttl($key) < 0) {
$redis->expire($key, 86400);
}
});
if ($result) {
echo "Success\n";
} else {
die('Error');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment