Memcached::getAllKeys
(PECL memcached >= 2.0.0)
Memcached::getAllKeys — Gets the keys stored on all the servers
Описание
public array Memcached::getAllKeys
( void
)
Memcached::getAllKeys() queries each memcache server and retrieves an array of all keys stored on them at that point in time. This is not an atomic operation, so it isn't a truly consistent snapshot of the keys at point in time. As memcache doesn't guarantee to return all keys you also cannot assume that all keys have been returned.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Returns the keys stored on all the servers on success или FALSE
в случае возникновения ошибки.
- Функция Memcached::add() - Add an item under a new key
- Функция Memcached::addByKey() - Add an item under a new key on a specific server
- Функция Memcached::addServer() - Add a server to the server pool
- Функция Memcached::addServers() - Add multiple servers to the server pool
- Функция Memcached::append() - Append data to an existing item
- Функция Memcached::appendByKey() - Append data to an existing item on a specific server
- Функция Memcached::cas() - Compare and swap an item
- Функция Memcached::casByKey() - Compare and swap an item on a specific server
- Функция Memcached::__construct() - Create a Memcached instance
- Функция Memcached::decrement() - Decrement numeric item's value
- Функция Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
- Функция Memcached::delete() - Delete an item
- Функция Memcached::deleteByKey() - Delete an item from a specific server
- Функция Memcached::deleteMulti() - Delete multiple items
- Функция Memcached::deleteMultiByKey() - Delete multiple items from a specific server
- Функция Memcached::fetch() - Fetch the next result
- Функция Memcached::fetchAll() - Fetch all the remaining results
- Функция Memcached::flush() - Invalidate all items in the cache
- Функция Memcached::get() - Retrieve an item
- Функция Memcached::getAllKeys() - Gets the keys stored on all the servers
- Функция Memcached::getByKey() - Retrieve an item from a specific server
- Функция Memcached::getDelayed() - Request multiple items
- Функция Memcached::getDelayedByKey() - Request multiple items from a specific server
- Функция Memcached::getMulti() - Retrieve multiple items
- Функция Memcached::getMultiByKey() - Retrieve multiple items from a specific server
- Функция Memcached::getOption() - Retrieve a Memcached option value
- Функция Memcached::getResultCode() - Return the result code of the last operation
- Функция Memcached::getResultMessage() - Return the message describing the result of the last operation
- Функция Memcached::getServerByKey() - Map a key to a server
- Функция Memcached::getServerList() - Get the list of the servers in the pool
- Функция Memcached::getStats() - Get server pool statistics
- Функция Memcached::getVersion() - Get server pool version info
- Функция Memcached::increment() - Increment numeric item's value
- Функция Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server
- Функция Memcached::isPersistent() - Check if a persitent connection to memcache is being used
- Функция Memcached::isPristine() - Check if the instance was recently created
- Функция Memcached::prepend() - Prepend data to an existing item
- Функция Memcached::prependByKey() - Prepend data to an existing item on a specific server
- Функция Memcached::quit() - Close any open connections
- Функция Memcached::replace() - Replace the item under an existing key
- Функция Memcached::replaceByKey() - Replace the item under an existing key on a specific server
- Функция Memcached::resetServerList() - Clears all servers from the server list
- Функция Memcached::set() - Store an item
- Функция Memcached::setByKey() - Store an item on a specific server
- Функция Memcached::setMulti() - Store multiple items
- Функция Memcached::setMultiByKey() - Store multiple items on a specific server
- Функция Memcached::setOption() - Set a Memcached option
- Функция Memcached::setOptions() - Set Memcached options
- Функция Memcached::setSaslAuthData() - Set the credentials to use for authentication
- Функция Memcached::touch() - Set a new expiration on an item
- Функция Memcached::touchByKey() - Set a new expiration on an item on a specific server
Коментарии
First I use the lastest memcached version 1.4.25, but unfortunately I found memcached::getAllkeys do not work with it, though i follow the others suggestion to disable Memcached::OPT_BINARY_PROTOCOL. So i try to use history versions, when i use memcached version 1.4.17, it works.
// initiate the memcached instance
$cache = new \Memcached();
$cache->addServer('localhost', '11211');
// get all stored memcached items
$keys = $cache->getAllKeys();
$cache->getDelayed($keys);
$store = $cache->fetchAll();
// delete by regex keys
$keys = $cache->getAllKeys();
$regex = 'product_.*';
foreach($keys as $item) {
if(preg_match('/'.$regex.'/', $item)) {
$cache->delete($item);
}
}
/**
* Get all memcached keys. Special function because getAllKeys() is broken since memcached 1.4.23. Should only be needed on php 5.6
*
* cleaned up version of code found on Stackoverflow.com by Maduka Jayalath
*
* @return array|int - all retrieved keys (or negative number on error)
*/
public function getMemcachedKeys($host = '127.0.0.1', $port = 11211)
{
$mem = @fsockopen($host, $port);
if ($mem === false)
{
return -1;
}
// retrieve distinct slab
$r = @fwrite($mem, 'stats items' . chr(10));
if ($r === false)
{
return -2;
}
$slab = [];
while (($l = @fgets($mem, 1024)) !== false)
{
// finished?
$l = trim($l);
if ($l == 'END')
{
break;
}
$m = [];
// <STAT items:22:evicted_nonzero 0>
$r = preg_match('/^STAT\sitems\:(\d+)\:/', $l, $m);
if ($r != 1)
{
return -3;
}
$a_slab = $m[1];
if (!array_key_exists($a_slab, $slab))
{
$slab[$a_slab] = [];
}
}
reset($slab);
foreach ($slab as $a_slab_key => &$a_slab)
{
$r = @fwrite($mem, 'stats cachedump ' . $a_slab_key . ' 100' . chr(10));
if ($r === false)
{
return -4;
}
while (($l = @fgets($mem, 1024)) !== false)
{
// finished?
$l = trim($l);
if ($l == 'END')
{
break;
}
$m = [];
// ITEM 42 [118 b; 1354717302 s]
$r = preg_match('/^ITEM\s([^\s]+)\s/', $l, $m);
if ($r != 1)
{
return -5;
}
$a_key = $m[1];
$a_slab[] = $a_key;
}
}
// close the connection
@fclose($mem);
unset($mem);
$keys = [];
reset($slab);
foreach ($slab AS &$a_slab)
{
reset($a_slab);
foreach ($a_slab AS &$a_key)
{
$keys[] = $a_key;
}
}
unset($slab);
return $keys;
}
The right way to dump slab keys seems to be by using lru_crawler metadump instead of stats cachedump, see https://github.com/memcached/memcached/issues/405
<?php
function getAllKeys(string $host, int $port): array
{
$sock = fsockopen($host, $port, $errno, $errstr);
if ($sock === false) {
throw new Exception("Error connection to server {$host} on port {$port}: ({$errno}) {$errstr}");
}
if (fwrite($sock, "stats items\n") === false) {
throw new Exception("Error writing to socket");
}
$slabCounts = [];
while (($line = fgets($sock)) !== false) {
$line = trim($line);
if ($line === 'END') {
break;
}
// STAT items:8:number 3
if (preg_match('!^STAT items:(\d+):number (\d+)$!', $line, $matches)) {
$slabCounts[$matches[1]] = (int)$matches[2];
}
}
foreach ($slabCounts as $slabNr => $slabCount) {
if (fwrite($sock, "lru_crawler metadump {$slabNr}\n") === false) {
throw new Exception('Error writing to socket');
}
$count = 0;
while (($line = fgets($sock)) !== false) {
$line = trim($line);
if ($line === 'END') {
break;
}
// key=foobar exp=1596440293 la=1596439293 cas=8492 fetch=no cls=24 size=14908
if (preg_match('!^key=(\S+)!', $line, $matches)) {
$allKeys[] = $matches[1];
$count++;
}
}
// if ($count !== $slabCount) {
// throw new Exception("Surprise, got {$count} keys instead of {$slabCount} keys");
// }
}
if (fclose($sock) === false) {
throw new Exception('Error closing socket');
}
return $allKeys;
}