Tuesday, 20 August 2013

Intermittent null data returned by memcache on get method

Intermittent null data returned by memcache on get method

I'm running memcached and my application is using the php libmemcached.
The code itself is a simple check key exists, if not pull fresh from mysql
database with an 'x' amount of expiry time.
I have an array of data I pull from mysql which is returned via another
method as an array - this is stored into memcached under the key
'menudata_array'. Everything was fine until I noticed sometimes the
menudata was being returned from the caching method as null or empty???
The only bit of info I have is that when the menudata is returned
empty|null, the period of error is equal to the expiry timeout of 120
seconds ?? After which the next request for data is returned ok.
I'm sure i've misunderstood something here!
The code is as follows:
function getMenuData()
{
$menudata_array = array(); //init an empty array
$memcache = getMemcache(); //method returns an instance of memcache
(global) or false is failure
if($memcache)
{
//get from memcache
$menudata_array = $memcache->get('menudata_array');
//make sure something was returned
if($menudata_array === false)
{
$menudata_array = generate_menu_array(); // get from mysql db
$expire_seconds = 120;
$refresh = $memcache->add('menudata_array', $menudata_array, false,
$expire_seconds);
if($refresh === false)
{
//key already exists so replace instead ...
$memcache->replace('menudata_array', $menudata_array, false,
$expire_seconds);
}
}
}
else
{
//memcache not available|down... get from mysql db instead
$menudata_array = generate_menu_array();
}
//i added this line to track when this problem was happening ...
if(!$menudata_array || count($menudata_array)<=0)
{
logError();
}
return $menudata_array;
}
Any help/pointers appreciated!

No comments:

Post a Comment