Last active
January 3, 2017 10:21
-
-
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
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
$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