Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does setting a memcached key that already exists refresh the expiration time?

Tags:

memcached

Let's say I have the following code:

Memcached->set('key', 'value', 60); (expire in one minute)

while (1) {
    sleep 1 second;
    data = Memcached->get('key');
    // update data
    Memcached->set('key', data, 60);
}

After 60 iterations of the loop, will the key expire and when reading it I'll get a NULL? Or will the continuous setting keep pushing the expiration time each time to 1 minute after the last Set?

The documentation mentions this, and I've tested this in different contexts and I'm pretty sure I got different results.

like image 705
Daniel Magliola Avatar asked May 20 '11 02:05

Daniel Magliola


People also ask

How do I set the expiration date on Memcached?

You can set key expiration to a date, by supplying a Unix timestamp instead of a number of days. This date can be more than 30 days in the future: Expiration times are specified in unsigned integer seconds. They can be set from 0, meaning "never expire", to 30 days (60*60*24*30).

Does memcached support TTL?

Memcached uses lazy expiration to remove keys when the time to live (TTL) expires. This means that the key isn't removed from the node even though it's expired. However, when someone tries to access an expired key, Memcached checks the key, identifies that the key is expired, and then removes it from memory.

How much data can memcache store?

The following limits apply to the use of the memcache service: The maximum size of a cached data value is 1 MB (10^6 bytes). A key cannot be larger than 250 bytes.


2 Answers

Ok, found my answer by experimentation in the end...

It turns out "Set" does extend the expiration, it's basically the same as deleting the item and Setting it again with a new expiration.

However, Increment doesn't extend the expiration. If you increment a key, it keeps the original expiration time it had when you Set it in the first place.

like image 152
Daniel Magliola Avatar answered Jan 01 '23 09:01

Daniel Magliola


If you simply want to extend the expiration time for a particular key instead of essentially resetting the data each time, you can just use Memcached::touch

With the caveat that you must have binary protocol enabled according to the comment on the above page.

$memcached = new Memcached();
$memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$memcached->touch('key', 120);
like image 23
nateevans Avatar answered Jan 01 '23 09:01

nateevans