A CMS I use implements memcached by default and I'm working to expand it. One key contains an array of user information, like userstats_id
and contains information like forum post counts, number of posts they've liked blah blah. The key looks like this:
[userstats_1] => Array
(
[forum_posts] => 178
[forum_likes] => 16
[forum_dislikes] => 0
[now_online] => 1
)
I'm expanding the usage of this key because I also want to store which specific forums the user is browsing, e.g.:
[userstats_forumbrowsing_1] => Array
(
[forum_browsing] => 'Foobar'
)
It would be better if I could have this within [userstats_1] as of course that makes more sense. So given also that this changes a lot more frequently than the rest of the elements of that cached array, what's the best way to get and set the elements of the cached array?
The only way I have come up with is to copy the array, manipulate it then re-set it in the cache, but that seems crazy. Thanks!
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.
First, when memcached gets full, it will start removing items from the cache using the Least Recently Used algorithm. Second, you can have multiple instances of memcached running, adding them gets complicated because it will change the hashing algorithm used to determine which cache the data is in.
When deciding whether to use Redis or Memcached a major difference between these two is data persistence. While Redis is an in-memory (mostly) data store and it is not volatile, Memcached is an in-memory cache and it is volatile.
No, unfortunately because memcached is a simple key-value store you cannot modify or access just part of a value addressed by a single key.
So you have two choices:
get
the entire array, modify one element, and then set
the entire array.get
and set
them separately.Which is better depend on the relative sizes of the parts, their pattern of usage, and how important it is to maintain consistency.
Or another choice is to not use memcached, and instead use Redis, which extends the simple key-value model to include data types, including hashes that support the kind of updates you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With