Memcache get key expiry times

18,173

Solution 1

No, that kind of data is not retrievable from the client end. If you really need it, store it together with the data in a serialized array or something. Also, check out this post just in case you were trying to do something similar.

Solution 2

Use this example. It shows all your server keys with their expire datetimes, so you can get the current key's expiry time.

function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('192.168.1.18', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs as $slabId => $slabMeta) {
           if (!is_numeric($slabId)) {
                continue;
           } 
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                if (!is_array($arrVal)) continue;
                foreach($arrVal AS $k => $v) {                   
                    echo $k .' - '.date('H:i d.m.Y',$v[1]).'<br />';
                }
           }
        }
    }   
}

Solution 3

Three notes about the Jason's snippet:

  1. there is a limit of 2 Mega in the cachedump reply message, so you must verify if there are all the stored keys in the answer, you can get the real number stored keys in $slabMeta['used_chunks'].

  2. Memcached keeps expired keys until someone get them; if you want to get the expiration time of valid keys only you can try to get the values of all those returned by cachedump. Running this procedure many times you can remove all expired keys and maximize the possibility to read all keys (see the limitation at point 1)

  3. in the memcached (old) version 1.2.2 the value returned into $v[1] is the key creation time and not the key expire time, in this version there isn't a way to get the expiration time of a key

Share:
18,173
Tom
Author by

Tom

Updated on June 04, 2022

Comments

  • Tom
    Tom almost 2 years

    Using memcached and the php memcached library, is there a way to get the current keys expiry time when doing a get?