tags:

views:

83

answers:

4

Hey!

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.

A: 

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?

pakore
Yes, but I first need to be sure it's not set already. Because if it's already set, then I'd waste reading the data from a slow source. If I use get() to check, then I will waste network IO because the value is 1MB is size.
Matic
+2  A: 

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.

Thariama
And if it returns true, don't forget to do a Memcached::delete after
Serty Oan
@Serty Oan: both wrote the same time :)
Thariama
@Thariama : great minds think alike ;)
Serty Oan
A: 

This makes no sense from Memcached perspective. If you want to avoid the slow datasource (by a scheduled job, I presume?), save the data to a faster but still stable datasource (e.g. a file) in your scheduled job. When you need the data, try to read from Memcached first, and if that fails read the file and save it into Memcached.

Memcached cannot give you a good answer, as pakore have already answered. The architecture is not meant to be a stable datasource.

Emil Vikström
A: 

I've solved this by using Memcached::append. I try appending value NULL and if it returns TRUE, it means the key exists. If it returns FALSE it means the key doesn't exist. If the key exist it will also put it on top of LRU list.

Thank you for your answers.

Matic