When and how do you update a changed item in Memcached?
I'm using PHP's PECL/Memcached for the first time and I can't figure out when or how I should be updating changed items in Memcached.
I've tried using both Memcached::add
and Memcached::set
and neither yields the results I expect.
Memcached::set
replaces the value automatically
$memcached->set('key', 'value', time() + 300);
$memcached->set('key', 'value2', time() + 300);
var_dump($memcached->get('key')开发者_JAVA百科); // Outputs "value2"
and Memcached::add
won't replace the value if it's already set in Memcached
$memcached->add('key', 'value');
$memcached->add('key', 'value2';
var_dump($memcached->get('key')); // Outputs "value"
So what's the typical practice for updating values in Memcached?
You call memcached::get.
If the return value is not false, your value was in the cache and you now have it and can make use of it.
If the return value is false, it's not in the cache (never was or what was there has expired). Compute the value, save it into your memcache, then continue with your program.
The purpose of the cache is to save you from doing some resource-intensive task by doing it once, then caching it for a while and reusing the value on future requests.
精彩评论