Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a key exists in Memcache

Tags:

php

memcached

How do I check in PHP if a value is stored in Memcache without fetching it? I don't like fetching it because the values I have set are all 1MB in size and after I fetch it, I have no use for it, so I'm wasting resources. I'm using this in a script that checks if certain keys are cached in memcache and if not, it reads them from a slow data source and sets them in memcache.

Edit: What if I use Memcached::append to append NULL to the key I'm checking? Returns TRUE on success or FALSE on failure. The Memcached::getResultCode will return Memcached::RES_NOTSTORED if the key does not exist. This way I check whether the key exists and it should put the key on top of the LRU list right?

Thank you.

like image 474
Matic Avatar asked Jun 22 '10 07:06

Matic


3 Answers

I am not sure if this is of any help to you, but you can use

Memcache::add  (  string $key  ,  mixed $var)

It will return false if the key already exists.

In case true is returned you may use

Memcache::delete  (  string $key)

to remove the key you just set. That way you won't need to fetch the data.

like image 153
Thariama Avatar answered Nov 08 '22 07:11

Thariama


I wonder why Memcached has no special method for it. Here is what I came down to after some considerations:

function has($key)
{
    $m->get($key)

    return \Memcached::RES_NOTFOUND !== $m->getResultCode();
}
like image 8
user487772 Avatar answered Nov 08 '22 07:11

user487772


Basically what you want to do is to fill memcached with your data, right?

The thing is that asking if a key is there withouth retrieving the value is not very useful. See this case scenario:

You ask if a key exists and it does. Just after you ask, the data of the key is expelled from the cache. While your response is coming back saying that the date is there, the reality is that the data is not there. So you lost time asking, because the answer is different from reality.

I guess what you want to do is to ask if a key exists, and then if it does not, fill it with your data. Why don't you fill directly all the data? Btw, have you considered that while you are filling memcached with data, you could be expelling keys you just previously inserted?

like image 3
pakore Avatar answered Nov 08 '22 07:11

pakore