I recently made a change to my User class (which is memcached); is there any way I can invalidate all entries whose key begins with User
without invalidating the entire cache?
If not are there any workarounds? I would rather not delete everything.
Webmasters Stack Exchange is a question and answer site for pro webmasters. It only takes a minute to sign up.
Sign up to join this communityI recently made a change to my User class (which is memcached); is there any way I can invalidate all entries whose key begins with User
without invalidating the entire cache?
If not are there any workarounds? I would rather not delete everything.
In the memcached FAQ, Deleting by Namespace:
While memcached does not support any type of wildcard deleting or deletion by namespace (since there are not namespaces), there are some tricks that can be used to simulate this. They do require extra trips to the memcached servers however.
Example, in PHP, for using a namespace called foo:
$ns_key = $memcache->get("foo_namespace_key");
// if not set, initialize it
if($ns_key===false) $memcache->set("foo_namespace_key", rand(1, 10000));
// cleverly use the ns_key
$my_key = "foo_".$ns_key."_12345";
$my_val = $memcache->get($my_key);
//To clear the namespace do:
$memcache->increment("foo_namespace_key");
If you are planning on doing a blanket clear of only part of the cache, you might consider setting the expiry to a shorter time period.
As memcached does not have namespace or something like delete/query by wildcards, you can do this trick: save all keys starts with namespace "user_" in a key.
For example
$keys = array('user_1', 'user_2', 'user_3');
$memcache->set('user_', $keys);
Now when you want to delete all keys starts with "user_", just get key "user_" first. By doing that, you have all keys you want do delete
$all_keys = $memcache->get('user_');
if($all_keys){
foreach($all_keys as $key){
$memcache->delete($key);
}
}