Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memcache get key expiry times

Tags:

php

memcached

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

like image 587
Tom Avatar asked Mar 16 '11 17:03

Tom


3 Answers

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 />';
                }
           }
        }
    }   
}
like image 56
Cyrill Avatar answered Nov 11 '22 13:11

Cyrill


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.

like image 40
ryeguy Avatar answered Nov 11 '22 13:11

ryeguy


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

like image 30
mop Avatar answered Nov 11 '22 12:11

mop